配置文件:

 #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
logging配置
""" import os
import logging.config # 定义三种日志输出格式 开始 standard_format = '[%(asctime) -s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
'[%(levelname)s][%(message)s]' simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s' id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s' # 定义日志输出格式 结束 logfile_dir = os.path.dirname(os.path.abspath(__file__)) # log文件的目录 logfile_name = 'all2.log' # log文件名 # 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir):
os.mkdir(logfile_dir) # log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name) # log配置字典
LOGGING_DIC = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': standard_format,
'datefmt': '%Y-%m-%d %H:%M:%S',
},
'simple': {
'format': simple_format
},
},
'filters': {},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler', # 打印到屏幕
'formatter': 'simple'
},
'default': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件
'filename': logfile_path, # 日志文件
'maxBytes': 1024*1024*5, # 日志大小 5M
'backupCount': 5,
'formatter': 'standard',
'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了
},
},
'loggers': {
'': {
'handlers': ['default', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
'level': 'DEBUG',
'propagate': True, # 向上(更高level的logger)传递
},
},
}
logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的配置
logger = logging.getLogger(__name__) # 生成一个log实例
logger.info('It works!') # 记录该文件的运行状态

调用测试文件:

 #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
MyLogging Test
""" import time
import logging
from log_demo import my_logging # 导入自定义的logging配置 logger = logging.getLogger(__file__) # 生成logger实例 def demo():
logger.debug("start range... time:{}".format(time.time()))
logger.info("中文测试开始。。。")
for i in range(10):
logger.debug("i:{}".format(i))
time.sleep(2)
else:
logger.debug("over range... time:{}".format(time.time()))
logger.info("中文测试结束。。。") if __name__ == "__main__":
demo()

Django配置:

 #! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Q1mi"
# Date: 2017/7/28 LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'
'[%(levelname)s][%(message)s]'
},
'simple': {
'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
},
'collect': {
'format': '%(message)s'
}
},
'filters': {
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'handlers': {
#打印到终端的日志
'console': {
'level': 'DEBUG',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
#打印到文件的日志,收集info及以上的日志
'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "xxx_info.log"), # 日志文件
'maxBytes': 1024 * 1024 * 5, # 日志大小 5M
'backupCount': 3,
'formatter': 'standard',
'encoding': 'utf-8',
},
#打印到文件的日志:收集错误及以上的日志
'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "xxx_err.log"), # 日志文件
'maxBytes': 1024 * 1024 * 5, # 日志大小 5M
'backupCount': 5,
'formatter': 'standard',
'encoding': 'utf-8',
},
#打印到文件的日志
'collect': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "xxx_collect.log"),
'maxBytes': 1024 * 1024 * 5, # 日志大小 5M
'backupCount': 5,
'formatter': 'collect',
'encoding': "utf-8"
}
},
'loggers': {
#logging.getLogger(__name__)拿到的logger配置
'': {
'handlers': ['default', 'console', 'error'],
'level': 'DEBUG',
'propagate': True,
},
#logging.getLogger('collect')拿到的logger配置
'collect': {
'handlers': ['console', 'collect'],
'level': 'INFO',
}
},
} # -----------
# 用法:拿到俩个logger logger = logging.getLogger(__name__) #线上正常的日志
collect_logger = logging.getLogger("collect") #领导说,需要为领导们单独定制领导们看的日志

最新文章

  1. SQL*Plus环境下创建PLUSTRACE角色
  2. C#事件学习
  3. Python 开发轻量级爬虫08
  4. GDB 和 windbg 命令对照(转载)
  5. JavaScript简介及基础知识(1)
  6. HTTP长连接短连接
  7. MVC学习系列——HtmlHelper扩展
  8. java InputStream
  9. linux命令11
  10. IT行业歧视40岁以上人群为找工作还要谎报年龄[转]
  11. Jenkins持续集成环境, 如何自定义 maven 仓库
  12. ps使用经验
  13. servlet操作本地文件汇总: 判断文件是否存在;文件重命名;文件复制; 获取文件属性信息,转成Json对象; 获取指定类型的文件; 查找替换.txt中的文本
  14. ueditor的简单用法
  15. [持续交付实践] 开篇:持续集成&持续交付综述
  16. POJ 1502 MPI Maelstrom / UVA 432 MPI Maelstrom / SCU 1068 MPI Maelstrom / UVALive 5398 MPI Maelstrom /ZOJ 1291 MPI Maelstrom (最短路径)
  17. Haskell语言学习笔记(39)Category
  18. VC6 快捷键
  19. c语言二维数组与指针
  20. IBatis Map报错10.1

热门文章

  1. 编写Servlet,验证用户登录,如果用户名与密码都为“admin”则验证通过,跳转欢迎页面,否则弹出提示信息“用户名或密码错误,请重新输入!”,点击“确定”后跳转至登录页面
  2. 一点对Promise的理解与总结
  3. MySQL——数据库和 SQL 概念&&MySQL的安装
  4. gzip, gunzip, zcat - 压缩或展开文件
  5. python_79_模块定义导入优化
  6. Nat Nanotechnol | 朱涛/陈春英等合作发现碳纳米管呼吸暴露后的延迟毒性导致小鼠原位乳腺肿瘤的多发性广泛转移
  7. RenderBody,RenderPage和RenderSection
  8. EWS code return Error : Request failed. The remote server returned an error: (403) Forbidden OR (401) Unauthorized
  9. 2d游戏中的射线与矩形检测碰撞
  10. PostgreSQL学习(1)-- 安装pageinspect extension