Skip to content

Commit 3c06c6c

Browse files
committed
Simple logging setup.
0 parents  commit 3c06c6c

2 files changed

Lines changed: 91 additions & 0 deletions

File tree

simpledaemonlog/__init__.py

Whitespace-only changes.

simpledaemonlog/logsetup.py

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
"""logsetup.py: A simple python logging setup for console and local log files."""
2+
3+
__author__ = 'Raido Pahtma'
4+
__license__ = "MIT"
5+
6+
import os
7+
import time
8+
import sys
9+
10+
DEFAULT_FORMAT_STRING = '%(asctime)s|%(levelname)8s|%(name)10s|%(lineno)3s| %(message)s'
11+
12+
13+
class StdLogger(object):
14+
def __init__(self, out, log):
15+
self._out = out
16+
self._log = log
17+
self.isatty = sys.__stdout__.isatty()
18+
19+
def _wrt_flt_std_log(self, txt):
20+
if len(txt) > 0:
21+
self._log(txt)
22+
23+
def write(self, txt):
24+
self._out.write(txt)
25+
self._wrt_flt_std_log(txt.rstrip())
26+
27+
28+
class PrintfFilter(object):
29+
30+
def filter(self, record):
31+
if record.funcName == "_wrt_flt_std_log":
32+
return 0
33+
else:
34+
return True
35+
36+
37+
def setup_console(level=logging.NOTSET, fs=DEFAULT_FORMAT_STRING):
38+
console = logging.StreamHandler()
39+
console.addFilter(PrintfFilter())
40+
41+
formatter = logging.Formatter(fs)
42+
console.setFormatter(formatter)
43+
console.setLevel(level)
44+
45+
rootlogger = logging.getLogger("")
46+
rootlogger.setLevel(min(level, rootlogger.getEffectiveLevel()))
47+
rootlogger.addHandler(console)
48+
49+
50+
def setup_file(application_name, log_folder="log", level=logging.NOTSET, fs=DEFAULT_FORMAT_STRING):
51+
"""
52+
Directs printf to file with INFO level.
53+
"""
54+
if not os.path.isdir(log_folder):
55+
os.makedirs(log_folder)
56+
57+
utc = time.gmtime()
58+
ts = time.strftime("%Y%m%d_%H%M%S%Z", utc)
59+
60+
logfilename = "log_{}_{}.txt".format(application_name, ts)
61+
logfile = logging.FileHandler(os.path.join(log_folder, logfilename))
62+
63+
formatter = logging.Formatter(fs)
64+
logfile.setFormatter(formatter)
65+
logfile.setLevel(level)
66+
67+
rootlogger = logging.getLogger("")
68+
rootlogger.setLevel(min(level, rootlogger.getEffectiveLevel()))
69+
rootlogger.addHandler(logfile)
70+
71+
sys.stderr = StdLogger(sys.stderr, logging.error)
72+
sys.stdout = StdLogger(sys.stdout, logging.info)
73+
74+
75+
if __name__ == "__main__":
76+
setup_console()
77+
setup_file("logsetup_test")
78+
79+
import logging
80+
log = logging.getLogger(__name__)
81+
82+
log.info("A piece of info")
83+
log.debug("Some debug")
84+
log.warning("A small warning")
85+
log.error("A big error")
86+
try:
87+
raise TypeError("An ugly TypeError")
88+
except TypeError:
89+
log.exception("The description of an exception")
90+
91+
print("The fine print")

0 commit comments

Comments
 (0)