Skip to content

Instantly share code, notes, and snippets.

@sparkydogX
Last active January 3, 2019 02:03
Show Gist options
  • Save sparkydogX/08613192821ab9df16d4ae1ccdd83e80 to your computer and use it in GitHub Desktop.
Save sparkydogX/08613192821ab9df16d4ae1ccdd83e80 to your computer and use it in GitHub Desktop.
python中内置的logging模块使用示例
# 基础用法
import os
import logging
if __name__ == '__main__':
logging.basicConfig(filename='example.log',format='%(asctime)s %(process)s %(module)s %(message)s',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything
logging.error('oops')
#===================================================================================================================================#
#===================================================================================================================================#
# 实用代码, 同时输出到文件和屏幕. 可以在多个模块中logging
import logging
# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename='myapp.log',
filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.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 other 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.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment