模块图
代码
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # import logging # 【简单日志】 # logging.basicConfig(filename='log1.txt',level=logging.DEBUG) # logging.warning('错误') # 【logger handler format】 logger=logging.getLogger('abc') logger.setLevel(logging.DEBUG) fh=logging.FileHandler(filename='filehandler.log.txt',mode='a',encoding='utf-8') fh.setLevel(logging.WARNING) formatter=logging.Formatter('%(message)s') fh.setFormatter(formatter) logger.addHandler(fh) logger.debug('debug') logger.info('info') logger.warning('warning') logger.error('error') logger.critical('critical') logger.critical('中文')
或者加入到两个handler处理
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # import logging # 【简单日志】 # logging.basicConfig(filename='log1.txt',level=logging.DEBUG) # logging.warning('错误') # 【logger handler format】 logger=logging.getLogger('abc') logger.setLevel(logging.DEBUG) fh=logging.FileHandler(filename='filehandler.log.txt',mode='a',encoding='utf-8') sh=logging.StreamHandler() fh.setLevel(logging.WARNING) formatter=logging.Formatter('%(message)s') fh.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(sh) logger.debug('debug') logger.info('info') logger.warning('warning') logger.error('error') logger.critical('critical') logger.critical('中文')
yaml配置文件方式 (另一种ini配置文件方式可读性差略)
logging.conf.yaml
version: 1 formatters: simple: format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' handlers: console: class: logging.StreamHandler level: DEBUG formatter: simple stream: ext://sys.stdout fh: class: logging.FileHandler level: DEBUG filename: log.txt mode: a encoding: utf-8 loggers: simpleExample: level: DEBUG handlers: [console,fh] propagate: no root: level: DEBUG handlers: [console]
py ( pip install pyyaml )
#!/usr/bin/env python3 # _*_ coding:utf-8 _*_ # import logging import logging.config # 注意 import yaml f=open('logging.conf.yaml') dic=yaml.load(f) print(dic) f.close() logging.config.dictConfig(dic) logger = logging.getLogger('simpleExample') logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message') logger.critical('中文')
附:另一个yaml配置文件参考
version: 1 disable_existing_loggers: False formatters: simple: format: "%(asctime)s - %(filename)s - %(levelname)s - %(message)s" handlers: console: class: logging.StreamHandler level: ERROR formatter: simple stream: ext://sys.stdout info_file_handler: class: logging.handlers.RotatingFileHandler level: INFO formatter: simple filename: ./mylog/info.log maxBytes: 10485760 # 10MB backupCount: 20 encoding: utf8 error_file_handler: class: logging.handlers.RotatingFileHandler level: ERROR formatter: simple filename: errors.log maxBytes: 10485760 # 10MB backupCount: 20 encoding: utf8 loggers: my_module: level: ERROR handlers: [console] propagate: no root: level: INFO handlers: [console, info_file_handler]
format参数
%(name)s Logger的名字 %(levelno)s 数字形式的日志级别 %(levelname)s 文本形式的日志级别 %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有 %(filename)s 调用日志输出函数的模块的文件名 %(module)s 调用日志输出函数的模块名 %(funcName)s 调用日志输出函数的函数名 %(lineno)d 调用日志输出函数的语句所在的代码行 %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示 %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数 %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 %(thread)d 线程ID。可能没有 %(threadName)s 线程名。可能没有 %(process)d 进程ID。可能没有 %(message)s用户输出的消息
part2 django中的logging
配置 (dict方式,内容类似yaml)
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'special': { '()': 'project.logging.SpecialFilter', 'foo': 'bar', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'filters': ['special'] } }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, }, 'myproject.custom': { 'handlers': ['console', 'mail_admins'], 'level': 'INFO', 'filters': ['special'] } } }
view中使用
# 导入logging库 import logging # 获取一个logger对象 logger = logging.getLogger(__name__) def my_view(request, arg1, arg): ... if bad_mojo: # 记录一个错误日志 logger.error('Something went wrong!')