Https://docs.python.org/3/howto/logging.html#logging-basic-tutorial
More and better examples:
Https://docs.python.org/3/howto/logging-cookbook.html#logging-cookbook
ImportLogging#set up logging to File-see previous sections for more detailsLogging.basicconfig (level=logging. DEBUG, Format='% (asctime) s% (name) -12s% (levelname) -8s% (message) s', Datefmt='%m-%d%h:%m', filename='/temp/myapp.log', FileMode='W')#define a Handler which writes INFO messages or higher to the Sys.stderrconsole =logging. Streamhandler () console.setlevel (logging.info)#set a format which is simpler for console useFormatter = logging. Formatter ('% (name) -12s:% (levelname) -8s% (message) s')#Tell the handler-use this formatConsole.setformatter (Formatter)#add the handler to the root loggerLogging.getlogger ("'). AddHandler (console)#Now , we can log to the root logger, or any other logger. First the root ...Logging.info ('jackdaws Love My big sphinx of quartz.')#Now , define a couple of all loggers which might represent areas in your#Application:Logger1= Logging.getlogger ('myapp.area1') Logger2= Logging.getlogger ('myapp.area2') Logger1.debug ('Quick zephyrs Blow, vexing daft Jim.') Logger1.info ('How quickly daft jumping zebras vex.') logger2.warning ('Jail Zesty Vixen who grabbed pay from quack.') Logger2.error ('The five boxing wizards jump quickly.')
When you run this, on the console you'll see
Root : INFO jackdaws Love My big sphinx of Quartz.myapp.area1:INFO how quickly daft jumping zebras vex.my App.area2:WARNING Jail Zesty Vixen who grabbed pay from Quack.myapp.area2:ERROR the five boxing wizards jump Quickly.
And in the file you'll see something like
Ten- A A: +root INFO jackdaws love my big sphinx of quartz.Ten- A A: +myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.Ten- A A: +myapp.area1 INFO How quickly daft jumping zebras vex.Ten- A A: +myapp.area2 WARNING Jail Zesty Vixen who grabbed pay from quack.Ten- A A: +MYAPP.AREA2 ERROR The five boxing wizards jump quickly.
Python Logging Learning Notes