-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlogging_formatter.py
87 lines (70 loc) · 2.47 KB
/
logging_formatter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import sys
sys.dont_write_bytecode = True
from datetime import datetime, timezone
import logging
import csv
import io
import os
def get_datetime():
datetimestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S:%f")
return datetimestamp
def get_datestamp():
datestamp = get_datetime().split()[0]
return datestamp
def get_timestamp():
timestamp = get_datetime().split()[1]
return timestamp
def get_year():
year = get_datestamp().split("-")[0]
return year
Year = get_year()
# Inspired by this discussion topic:
# https://stackoverflow.com/questions/19765139/what-is-the-proper-way-to-do-logging-in-csv-file
class CsvFormatter(logging.Formatter):
def __init__(self, filename="temp"):
super().__init__() # calls the init method of the Formatter class
self.output = io.StringIO()
self.filename = filename
self.fieldnames = ["Date", "Time", "Level", "Message"]
self.csvfile = None
# Serves as FileHandler
# ----------------------------- #
if os.path.isfile(self.filename):
self.csvfile = open(self.filename, "a+", newline="", encoding="utf-8")
self.file_writer = csv.DictWriter(
self.csvfile,
quoting=csv.QUOTE_ALL,
fieldnames=self.fieldnames,
extrasaction="ignore",
)
else:
self.csvfile = open(self.filename, "w+", newline="", encoding="utf-8")
self.file_writer = csv.DictWriter(
self.csvfile,
quoting=csv.QUOTE_ALL,
fieldnames=self.fieldnames,
extrasaction="ignore",
)
self.file_writer.writeheader()
# ----------------------------- #
# Serves as StreamHandler
self.console_writer = csv.writer(
self.output, quoting=csv.QUOTE_MINIMAL, delimiter="\t"
)
def format(self, record):
# Store datetime objects as variables to synchronise timestamps on both writers
Date = get_datestamp()
Time = get_timestamp()
self.file_writer.writerow(
dict(
Date=Date,
Time=Time,
Level=record.levelname,
Message=record.msg,
)
)
self.console_writer.writerow([Date, Time, record.levelname, record.msg])
data = self.output.getvalue()
self.output.truncate(0)
self.output.seek(0)
return data.strip()