I am looking for specific advice on how to make multiple protocols and multiple handler handlers. I added my simplified code here, but I don't want to give in to the answers - tell me what is the best practice.
I would like to write everything to a file and warn and higher for the console.
This is my level0.py , which I want it to register in the specified file:
import logging from flask import Flask from level1 import function1 app = Flask(__name__) logger = logging.getLogger('logger0') logger.setLevel(logging.DEBUG) file_handler = logging.FileHandler('../logs/logger0','w','utf-8') file_handler.setLevel(logging.DEBUG) file_format = logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d in %(funcName)s]') file_handler.setFormatter(file_format) logger.addHandler(file_handler) console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_format = logging.Formatter('%(message)s') console_handler.setFormatter(console_format) logger.addHandler(console_handler) @app.route('/', methods=['GET', 'POST']) def function0(foo): bar = function1(foo) logger.debug('function0') ...
In addition, level1 can be a standalone module when calling a script. In this case, I want it to be registered in another file. Below is level1.py (has duplicate logging lines):
import logging logger = logging.getLogger('level0.level1') from level2 import function2 def function1(foo): bar = function2(foo) logger.debug('function1') ... if __name__ == "__main__": logger = logging.getLogger('logger0') logger.setLevel(logging.DEBUG) file_handler = logging.FileHandler('../logs/logger1','w','utf-8') file_handler.setLevel(logging.DEBUG) file_format = logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d in %(funcName)s]') file_handler.setFormatter(file_format) logger.addHandler(file_handler) console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_format = logging.Formatter('%(message)s') console_handler.setFormatter(console_format) logger.addHandler(console_handler) bar = function1('foo') logger.info('level1 main') ...
I copied this piece of the log from level0 because I needed the same log and it seemed intuitive to put it in the main one. level2 not autonomous, so it only has:
import logging logger = logging.getLogger('level0.level1.level2') def function2(foo): logger.info('function2') ....
I started with logging.basicSetup , but could not set the encoding for the file and continued to receive UnicodeEncodeError when trying to write strings without ascii:
logger.warn(u'foo bar {}'.format(NON_ASCII_STR))
(I still get an error message when the registrar sends a message to their parents)
So, what is the best log design for this case or in general - several modules (with the choice of encoding - I want utf-8)