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

本文共 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

你可能感兴趣的文章
完善String类([]、 +、 += 运算符重载)、>>和<<运算符重载
查看>>
一步一步从原理跟我学邮件收取及发送 13.mime格式与常见字符编码
查看>>
qeephp 记录下
查看>>
The repository 'http://cdn.debian.net/debian stretch Release' is not signed.
查看>>
应用ImageJ对荧光图片进行半定量分析
查看>>
误判心理学常见心理倾向
查看>>
(转)同一服务器部署多个tomcat时的端口号修改详情
查看>>
Git换行符是如何精确控制的
查看>>
c#基础操作
查看>>
【Spring boot】【gradle】idea新建spring boot+gradle项目
查看>>
数据绑定流程分析(校验)
查看>>
这是一份很详细的 Retrofit 2.0 使用教程(含实例讲解)
查看>>
angular 2 中可以注入接口吗?如何实现?
查看>>
针对ArcGIS Server 跨域问题的解释
查看>>
云区域(region),可用区(AZ),跨区域数据复制(Cross-region replication)与灾备(Disaster Recovery)(部分2)...
查看>>
word使用宏定义来统一设置图片大小
查看>>
树莓GPIO &&python
查看>>
Android项目实战(四十四):Zxing二维码切换横屏扫描
查看>>
Android 7.0 行为变更
查看>>
JDK自带方法实现RSA数字签名
查看>>