博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
logging模块
阅读量:7217 次
发布时间:2019-06-29

本文共 5074 字,大约阅读时间需要 16 分钟。

 模块图

 

代码

#!/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('中文')
View Code

 

yaml配置文件方式 (另一种ini配置文件方式可读性差略)

logging.conf.yaml

version: 1formatters:  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-8loggers:  simpleExample:    level: DEBUG    handlers: [console,fh]    propagate: noroot:  level: DEBUG  handlers: [console]

 py ( pip install pyyaml )

#!/usr/bin/env python3# _*_ coding:utf-8 _*_#import loggingimport logging.config  # 注意import yamlf=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: 1disable_existing_loggers: Falseformatters:    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: utf8loggers:    my_module:        level: ERROR        handlers: [console]        propagate: noroot:    level: INFO    handlers: [console, info_file_handler]
View Code

 

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 Code

view中使用

# 导入logging库import logging# 获取一个logger对象logger = logging.getLogger(__name__)def my_view(request, arg1, arg):    ...    if bad_mojo:        # 记录一个错误日志        logger.error('Something went wrong!')
View Code

 

转载于:https://www.cnblogs.com/infaaf/p/9201419.html

你可能感兴趣的文章
女友眼中的IT男
查看>>
Excel连接
查看>>
java基础-多线程学习
查看>>
WPF打印原理,自定义打印
查看>>
HTML5 5
查看>>
箭头css
查看>>
Python入门,以及简单爬取网页文本内容
查看>>
顺丰科技笔试回忆
查看>>
excel技巧
查看>>
通用防SQL注入漏洞程序(Global.asax方式)
查看>>
服务器进程为何通常fork()两次
查看>>
python中的logger模块
查看>>
9.3、理解作用域与全局变量
查看>>
ios序列化最终方案
查看>>
HttpMessageConverter 专题
查看>>
oracle系统包——dbms_random用法及order by 小结(转)
查看>>
android布局基础及范例:人人android九宫格布局
查看>>
Entity Framework数据库初始化四种策略
查看>>
hdu5033 Building (单调栈+)
查看>>
IIS服务器如何抗住高并发的客户端访问
查看>>