After reading the documentation on logging
, I know I can use code like this to perform simple logging:
import logging
def main():
logging.basicConfig(filename="messages.log",
level=logging.WARNING,
format='%(filename)s: '
'%(levelname)s: '
'%(funcName)s(): '
'%(lineno)d:\t'
'%(message)s')
logging.debug("Only for debug purposes\n")
logging.shutdown()
main()
However, I realised I don't know how to change the format of log messages on a per-logger basis, since basicConfig
is a module-level function. This code works for creating different loggers with different levels, names, etc. but is there a way to change the format of those log messages on a per-logger basis as well, in a way similar to basicConfig
?
import inspect
import logging
def function_logger(level=logging.DEBUG):
function_name = inspect.stack()[1][3]
logger = logging.getLogger(function_name)
logger.setLevel(level)
logger.addHandler(logging.FileHandler("{0}.log".format(function_name)))
return logger
def f1():
f1_logger = function_logger()
f1_logger.debug("f1 Debug message")
f1_logger.warning("f1 Warning message")
f1_logger.critical("f1 Critical message")
def f2():
f2_logger = function_logger(logging.WARNING)
f2_logger.debug("f2 Debug message")
f2_logger.warning("f2 Warning message")
f2_logger.critical("f2 Critical message")
def main():
f1()
f2()
logging.shutdown()
main()