一 日志级别

  1. CRITICAL = 50 #FATAL = CRITICAL
  2. ERROR = 40
  3. WARNING = 30 #WARN = WARNING
  4. INFO = 20
  5. DEBUG = 10
  6. NOTSET = 0 #不设置

二 默认级别为warning,默认打印到终端

  1. import logging
  2.  
  3. logging.debug('调试debug')
  4. logging.info('消息info')
  5. logging.warning('警告warn')
  6. logging.error('错误error')
  7. logging.critical('严重critical')
  8.  
  9. '''
  10. WARNING:root:警告warn
  11. ERROR:root:错误error
  12. CRITICAL:root:严重critical
  13. '''

三 为logging模块指定全局配置,针对所有logger有效,控制打印到文件中

  1. 可在logging.basicConfig()函数中通过具体参数来更改logging模块默认行为,可用参数有
  2. filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
  3. filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
  4. format:指定handler使用的日志显示格式。
  5. datefmt:指定日期时间格式。
  6. level:设置rootlogger(后边会讲解具体概念)的日志级别
  7. stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filenamestream两个参数,则stream参数会被忽略。
  8.  
  9. #格式
  10. %(name)sLogger的名字,并非用户名,详细查看
  11.  
  12. %(levelno)s:数字形式的日志级别
  13.  
  14. %(levelname)s:文本形式的日志级别
  15.  
  16. %(pathname)s:调用日志输出函数的模块的完整路径名,可能没有
  17.  
  18. %(filename)s:调用日志输出函数的模块的文件名
  19.  
  20. %(module)s:调用日志输出函数的模块名
  21.  
  22. %(funcName)s:调用日志输出函数的函数名
  23.  
  24. %(lineno)d:调用日志输出函数的语句所在的代码行
  25.  
  26. %(created)f:当前时间,用UNIX标准的表示时间的浮 点数表示
  27.  
  28. %(relativeCreated)d:输出日志信息时的,自Logger创建以 来的毫秒数
  29.  
  30. %(asctime)s:字符串形式的当前时间。默认格式是 2003-07-08 16:49:45,896”。逗号后面的是毫秒
  31.  
  32. %(thread)d:线程ID。可能没有
  33.  
  34. %(threadName)s:线程名。可能没有
  35.  
  36. %(process)d:进程ID。可能没有
  37.  
  38. %(message)s:用户输出的消息
  1. 可在logging.basicConfig()函数中通过具体参数来更改logging模块默认行为,可用参数有
  2. filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
  3. filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
  4. format:指定handler使用的日志显示格式。
  5. datefmt:指定日期时间格式。
  6. level:设置rootlogger(后边会讲解具体概念)的日志级别
  7. stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filenamestream两个参数,则stream参数会被忽略。
  8.  
  9. #格式
  10. %(name)sLogger的名字,并非用户名,详细查看
  11.  
  12. %(levelno)s:数字形式的日志级别
  13.  
  14. %(levelname)s:文本形式的日志级别
  15.  
  16. %(pathname)s:调用日志输出函数的模块的完整路径名,可能没有
  17.  
  18. %(filename)s:调用日志输出函数的模块的文件名
  19.  
  20. %(module)s:调用日志输出函数的模块名
  21.  
  22. %(funcName)s:调用日志输出函数的函数名
  23.  
  24. %(lineno)d:调用日志输出函数的语句所在的代码行
  25.  
  26. %(created)f:当前时间,用UNIX标准的表示时间的浮 点数表示
  27.  
  28. %(relativeCreated)d:输出日志信息时的,自Logger创建以 来的毫秒数
  29.  
  30. %(asctime)s:字符串形式的当前时间。默认格式是 2003-07-08 16:49:45,896”。逗号后面的是毫秒
  31.  
  32. %(thread)d:线程ID。可能没有
  33.  
  34. %(threadName)s:线程名。可能没有
  35.  
  36. %(process)d:进程ID。可能没有
  37.  
  38. %(message)s:用户输出的消息
  1. #======介绍
  2. 可在logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有
  3. filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
  4. filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
  5. format:指定handler使用的日志显示格式。
  6. datefmt:指定日期时间格式。
  7. level:设置rootlogger(后边会讲解具体概念)的日志级别
  8. stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filenamestream两个参数,则stream参数会被忽略。
  9.  
  10. format参数中可能用到的格式化串:
  11. %(name)s Logger的名字
  12. %(levelno)s 数字形式的日志级别
  13. %(levelname)s 文本形式的日志级别
  14. %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
  15. %(filename)s 调用日志输出函数的模块的文件名
  16. %(module)s 调用日志输出函数的模块名
  17. %(funcName)s 调用日志输出函数的函数名
  18. %(lineno)d 调用日志输出函数的语句所在的代码行
  19. %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
  20. %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
  21. %(asctime)s 字符串形式的当前时间。默认格式是 2003-07-08 16:49:45,896”。逗号后面的是毫秒
  22. %(thread)d 线程ID。可能没有
  23. %(threadName)s 线程名。可能没有
  24. %(process)d 进程ID。可能没有
  25. %(message)s用户输出的消息
  26.  
  27. #========使用
  28. import logging
  29. logging.basicConfig(filename='access.log',
  30. format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
  31. datefmt='%Y-%m-%d %H:%M:%S %p',
  32. level=10)
  33.  
  34. logging.debug('调试debug')
  35. logging.info('消息info')
  36. logging.warning('警告warn')
  37. logging.error('错误error')
  38. logging.critical('严重critical')
  39.  
  40. #========结果
  41. access.log内容:
  42. 2017-07-28 20:32:17 PM - root - DEBUG -test: 调试debug
  43. 2017-07-28 20:32:17 PM - root - INFO -test: 消息info
  44. 2017-07-28 20:32:17 PM - root - WARNING -test: 警告warn
  45. 2017-07-28 20:32:17 PM - root - ERROR -test: 错误error
  46. 2017-07-28 20:32:17 PM - root - CRITICAL -test: 严重critical
  47.  
  48. part2: 可以为logging模块指定模块级的配置,即所有logger的配置
  1. #======介绍
  2. 可在logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有
  3. filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
  4. filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
  5. format:指定handler使用的日志显示格式。
  6. datefmt:指定日期时间格式。
  7. level:设置rootlogger(后边会讲解具体概念)的日志级别
  8. stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filenamestream两个参数,则stream参数会被忽略。
  9.  
  10. format参数中可能用到的格式化串:
  11. %(name)s Logger的名字
  12. %(levelno)s 数字形式的日志级别
  13. %(levelname)s 文本形式的日志级别
  14. %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
  15. %(filename)s 调用日志输出函数的模块的文件名
  16. %(module)s 调用日志输出函数的模块名
  17. %(funcName)s 调用日志输出函数的函数名
  18. %(lineno)d 调用日志输出函数的语句所在的代码行
  19. %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
  20. %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
  21. %(asctime)s 字符串形式的当前时间。默认格式是 2003-07-08 16:49:45,896”。逗号后面的是毫秒
  22. %(thread)d 线程ID。可能没有
  23. %(threadName)s 线程名。可能没有
  24. %(process)d 进程ID。可能没有
  25. %(message)s用户输出的消息
  26.  
  27. #========使用
  28. import logging
  29. logging.basicConfig(filename='access.log',
  30. format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
  31. datefmt='%Y-%m-%d %H:%M:%S %p',
  32. level=10)
  33.  
  34. logging.debug('调试debug')
  35. logging.info('消息info')
  36. logging.warning('警告warn')
  37. logging.error('错误error')
  38. logging.critical('严重critical')
  39.  
  40. #========结果
  41. access.log内容:
  42. 2017-07-28 20:32:17 PM - root - DEBUG -test: 调试debug
  43. 2017-07-28 20:32:17 PM - root - INFO -test: 消息info
  44. 2017-07-28 20:32:17 PM - root - WARNING -test: 警告warn
  45. 2017-07-28 20:32:17 PM - root - ERROR -test: 错误error
  46. 2017-07-28 20:32:17 PM - root - CRITICAL -test: 严重critical
  47.  
  48. part2: 可以为logging模块指定模块级的配置,即所有logger的配置

四 logging模块的Formatter,Handler,Logger,Filter对象

原理图:https://pan.baidu.com/s/1skWyTT7

 
  1. #logger:产生日志的对象
  2.  
  3. #Filter:过滤日志的对象
  4.  
  5. #Handler:接收日志然后控制打印到不同的地方,FileHandler用来打印到文件中,StreamHandler用来打印到终端
  6.  
  7. #Formatter对象:可以定制不同的日志格式对象,然后绑定给不同的Handler对象使用,以此来控制不同的Handler的日志格式

'''
critical=50
error =40
warning =30
info = 20
debug =10
'''

import logging

#1、logger对象:负责产生日志,然后交给Filter过滤,然后交给不同的Handler输出
logger=logging.getLogger(__file__)

#2、Filter对象:不常用,略

#3、Handler对象:接收logger传来的日志,然后控制输出
h1=logging.FileHandler('t1.log') #打印到文件
h2=logging.FileHandler('t2.log') #打印到文件
h3=logging.StreamHandler() #打印到终端

#4、Formatter对象:日志格式
formmater1=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',)

formmater2=logging.Formatter('%(asctime)s : %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',)

formmater3=logging.Formatter('%(name)s %(message)s',)

#5、为Handler对象绑定格式
h1.setFormatter(formmater1)
h2.setFormatter(formmater2)
h3.setFormatter(formmater3)

#6、将Handler添加给logger并设置日志级别
logger.addHandler(h1)
logger.addHandler(h2)
logger.addHandler(h3)
logger.setLevel(10)

#7、测试
logger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
logger.critical('critical')

  1. '''
  2. critical=50
  3. error =40
  4. warning =30
  5. info = 20
  6. debug =10
  7. '''
  8.  
  9. import logging
  10.  
  11. #1、logger对象:负责产生日志,然后交给Filter过滤,然后交给不同的Handler输出
  12. logger=logging.getLogger(__file__)
  13.  
  14. #2、Filter对象:不常用,略
  15.  
  16. #3、Handler对象:接收logger传来的日志,然后控制输出
  17. h1=logging.FileHandler('t1.log') #打印到文件
  18. h2=logging.FileHandler('t2.log') #打印到文件
  19. h3=logging.StreamHandler() #打印到终端
  20.  
  21. #4、Formatter对象:日志格式
  22. formmater1=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
  23. datefmt='%Y-%m-%d %H:%M:%S %p',)
  24.  
  25. formmater2=logging.Formatter('%(asctime)s : %(message)s',
  26. datefmt='%Y-%m-%d %H:%M:%S %p',)
  27.  
  28. formmater3=logging.Formatter('%(name)s %(message)s',)
  29.  
  30. #5、为Handler对象绑定格式
  31. h1.setFormatter(formmater1)
  32. h2.setFormatter(formmater2)
  33. h3.setFormatter(formmater3)
  34.  
  35. #6、将Handler添加给logger并设置日志级别
  36. logger.addHandler(h1)
  37. logger.addHandler(h2)
  38. logger.addHandler(h3)
  39. logger.setLevel(10)
  40.  
  41. #7、测试
  42. logger.debug('debug')
  43. logger.info('info')
  44. logger.warning('warning')
  45. logger.error('error')
  46. logger.critical('critical')

五 Logger与Handler的级别

logger是第一级过滤,然后才能到handler,我们可以给logger和handler同时设置level,但是需要注意的是

Logger is also the first to filter the message based on a level — if you set the logger to INFO, and all handlers to DEBUG, you still won't receive DEBUG messages on handlers — they'll be rejected by the logger itself. If you set logger to DEBUG, but all handlers to INFO, you won't receive any DEBUG messages either — because while the logger says "ok, process this", the handlers reject it (DEBUG < INFO).

#验证
import logging

form=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',)

ch=logging.StreamHandler()

ch.setFormatter(form)
# ch.setLevel(10)
ch.setLevel(20)

l1=logging.getLogger('root')
# l1.setLevel(20)
l1.setLevel(10)
l1.addHandler(ch)

l1.debug('l1 debug')

重要,重要,重要!!!

  1. Logger is also the first to filter the message based on a level if you set the logger to INFO, and all handlers to DEBUG, you still won't receive DEBUG messages on handlers — they'll be rejected by the logger itself. If you set logger to DEBUG, but all handlers to INFO, you won't receive any DEBUG messages either — because while the logger says "ok, process this", the handlers reject it (DEBUG < INFO).
  2.  
  3. #验证
  4. import logging
  5.  
  6. form=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
  7. datefmt='%Y-%m-%d %H:%M:%S %p',)
  8.  
  9. ch=logging.StreamHandler()
  10.  
  11. ch.setFormatter(form)
  12. # ch.setLevel(10)
  13. ch.setLevel(20)
  14.  
  15. l1=logging.getLogger('root')
  16. # l1.setLevel(20)
  17. l1.setLevel(10)
  18. l1.addHandler(ch)
  19.  
  20. l1.debug('l1 debug')

六 Logger的继承(了解)

import logging

formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',)

ch=logging.StreamHandler()
ch.setFormatter(formatter)

logger1=logging.getLogger('root')
logger2=logging.getLogger('root.child1')
logger3=logging.getLogger('root.child1.child2')

logger1.addHandler(ch)
logger2.addHandler(ch)
logger3.addHandler(ch)
logger1.setLevel(10)
logger2.setLevel(10)
logger3.setLevel(10)

logger1.debug('log1 debug')
logger2.debug('log2 debug')
logger3.debug('log3 debug')
'''
2017-07-28 22:22:05 PM - root - DEBUG -test: log1 debug
2017-07-28 22:22:05 PM - root.child1 - DEBUG -test: log2 debug
2017-07-28 22:22:05 PM - root.child1 - DEBUG -test: log2 debug
2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test: log3 debug
2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test: log3 debug
2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test: log3 debug
'''

  1. import logging
  2.  
  3. formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
  4. datefmt='%Y-%m-%d %H:%M:%S %p',)
  5.  
  6. ch=logging.StreamHandler()
  7. ch.setFormatter(formatter)
  8.  
  9. logger1=logging.getLogger('root')
  10. logger2=logging.getLogger('root.child1')
  11. logger3=logging.getLogger('root.child1.child2')
  12.  
  13. logger1.addHandler(ch)
  14. logger2.addHandler(ch)
  15. logger3.addHandler(ch)
  16. logger1.setLevel(10)
  17. logger2.setLevel(10)
  18. logger3.setLevel(10)
  19.  
  20. logger1.debug('log1 debug')
  21. logger2.debug('log2 debug')
  22. logger3.debug('log3 debug')
  23. '''
  24. 2017-07-28 22:22:05 PM - root - DEBUG -test: log1 debug
  25. 2017-07-28 22:22:05 PM - root.child1 - DEBUG -test: log2 debug
  26. 2017-07-28 22:22:05 PM - root.child1 - DEBUG -test: log2 debug
  27. 2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test: log3 debug
  28. 2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test: log3 debug
  29. 2017-07-28 22:22:05 PM - root.child1.child2 - DEBUG -test: log3 debug
  30. '''

七 应用

"""
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]' #其中name为getlogger指定的名字

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
},
'simple': {
'format': simple_format
},
},
'filters': {},
'handlers': {
#打印到终端的日志
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler', # 打印到屏幕
'formatter': 'simple'
},
#打印到文件的日志,收集info及以上的日志
'default': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件
'formatter': 'standard',
'filename': logfile_path, # 日志文件
'maxBytes': 1024*1024*5, # 日志大小 5M
'backupCount': 5,
'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了
},
},
'loggers': {
#logging.getLogger(__name__)拿到的logger配置
'': {
'handlers': ['default', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
'level': 'DEBUG',
'propagate': True, # 向上(更高level的logger)传递
},
},
}

def load_my_logging_cfg():
logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的logging配置
logger = logging.getLogger(__name__) # 生成一个log实例
logger.info('It works!') # 记录该文件的运行状态

if __name__ == '__main__':
load_my_logging_cfg()

logging配置文件

  1. """
  2. logging配置
  3. """
  4.  
  5. import os
  6. import logging.config
  7.  
  8. # 定义三种日志输出格式 开始
  9.  
  10. standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
  11. '[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字
  12.  
  13. simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
  14.  
  15. id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
  16.  
  17. # 定义日志输出格式 结束
  18.  
  19. logfile_dir = os.path.dirname(os.path.abspath(__file__)) # log文件的目录
  20.  
  21. logfile_name = 'all2.log' # log文件名
  22.  
  23. # 如果不存在定义的日志目录就创建一个
  24. if not os.path.isdir(logfile_dir):
  25. os.mkdir(logfile_dir)
  26.  
  27. # log文件的全路径
  28. logfile_path = os.path.join(logfile_dir, logfile_name)
  29.  
  30. # log配置字典
  31. LOGGING_DIC = {
  32. 'version': 1,
  33. 'disable_existing_loggers': False,
  34. 'formatters': {
  35. 'standard': {
  36. 'format': standard_format
  37. },
  38. 'simple': {
  39. 'format': simple_format
  40. },
  41. },
  42. 'filters': {},
  43. 'handlers': {
  44. #打印到终端的日志
  45. 'console': {
  46. 'level': 'DEBUG',
  47. 'class': 'logging.StreamHandler', # 打印到屏幕
  48. 'formatter': 'simple'
  49. },
  50. #打印到文件的日志,收集info及以上的日志
  51. 'default': {
  52. 'level': 'DEBUG',
  53. 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件
  54. 'formatter': 'standard',
  55. 'filename': logfile_path, # 日志文件
  56. 'maxBytes': 1024*1024*5, # 日志大小 5M
  57. 'backupCount': 5,
  58. 'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了
  59. },
  60. },
  61. 'loggers': {
  62. #logging.getLogger(__name__)拿到的logger配置
  63. '': {
  64. 'handlers': ['default', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
  65. 'level': 'DEBUG',
  66. 'propagate': True, # 向上(更高level的logger)传递
  67. },
  68. },
  69. }
  70.  
  71. def load_my_logging_cfg():
  72. logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的logging配置
  73. logger = logging.getLogger(__name__) # 生成一个log实例
  74. logger.info('It works!') # 记录该文件的运行状态
  75.  
  76. if __name__ == '__main__':
  77. load_my_logging_cfg()

"""
MyLogging Test
"""

import time
import logging
import my_logging # 导入自定义的logging配置

logger = logging.getLogger(__name__) # 生成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(0.2)
else:
logger.debug("over range... time:{}".format(time.time()))
logger.info("中文测试结束。。。")

if __name__ == "__main__":
my_logging.load_my_logging_cfg() # 在你程序文件的入口加载自定义logging配置
demo()

使用

  1. """
  2. MyLogging Test
  3. """
  4.  
  5. import time
  6. import logging
  7. import my_logging # 导入自定义的logging配置
  8.  
  9. logger = logging.getLogger(__name__) # 生成logger实例
  10.  
  11. def demo():
  12. logger.debug("start range... time:{}".format(time.time()))
  13. logger.info("中文测试开始。。。")
  14. for i in range(10):
  15. logger.debug("i:{}".format(i))
  16. time.sleep(0.2)
  17. else:
  18. logger.debug("over range... time:{}".format(time.time()))
  19. logger.info("中文测试结束。。。")
  20.  
  21. if __name__ == "__main__":
  22. my_logging.load_my_logging_cfg() # 在你程序文件的入口加载自定义logging配置
  23. demo()

注意注意注意:

#1、有了上述方式我们的好处是:所有与logging模块有关的配置都写到字典中就可以了,更加清晰,方便管理

#2、我们需要解决的问题是:
1、从字典加载配置:logging.config.dictConfig(settings.LOGGING_DIC)

2、拿到logger对象来产生日志
logger对象都是配置到字典的loggers 键对应的子字典中的
按照我们对logging模块的理解,要想获取某个东西都是通过名字,也就是key来获取的
于是我们要获取不同的logger对象就是
logger=logging.getLogger('loggers子字典的key名')

但问题是:如果我们想要不同logger名的logger对象都共用一段配置,那么肯定不能在loggers子字典中定义n个key
'loggers': {
'l1': {
'handlers': ['default', 'console'], #
'level': 'DEBUG',
'propagate': True, # 向上(更高level的logger)传递
},
'l2: {
'handlers': ['default', 'console' ],
'level': 'DEBUG',
'propagate': False, # 向上(更高level的logger)传递
},
'l3': {
'handlers': ['default', 'console'], #
'level': 'DEBUG',
'propagate': True, # 向上(更高level的logger)传递
},

}

#我们的解决方式是,定义一个空的key
'loggers': {
'': {
'handlers': ['default', 'console'],
'level': 'DEBUG',
'propagate': True,
},

}

这样我们再取logger对象时
logging.getLogger(__name__),不同的文件__name__不同,这保证了打印日志时标识信息不同,但是拿着该名字去loggers里找key名时却发现找不到,于是默认使用key=''的配置

!!!关于如何拿到logger对象的详细解释!!!

  1. 注意注意注意:
  2.  
  3. #1、有了上述方式我们的好处是:所有与logging模块有关的配置都写到字典中就可以了,更加清晰,方便管理
  4.  
  5. #2、我们需要解决的问题是:
  6. 1、从字典加载配置:logging.config.dictConfig(settings.LOGGING_DIC)
  7.  
  8. 2、拿到logger对象来产生日志
  9. logger对象都是配置到字典的loggers 键对应的子字典中的
  10. 按照我们对logging模块的理解,要想获取某个东西都是通过名字,也就是key来获取的
  11. 于是我们要获取不同的logger对象就是
  12. logger=logging.getLogger('loggers子字典的key名')
  13.  
  14. 但问题是:如果我们想要不同logger名的logger对象都共用一段配置,那么肯定不能在loggers子字典中定义nkey
  15. 'loggers': {
  16. 'l1': {
  17. 'handlers': ['default', 'console'], #
  18. 'level': 'DEBUG',
  19. 'propagate': True, # 向上(更高level的logger)传递
  20. },
  21. 'l2: {
  22. 'handlers': ['default', 'console' ],
  23. 'level': 'DEBUG',
  24. 'propagate': False, # 向上(更高level的logger)传递
  25. },
  26. 'l3': {
  27. 'handlers': ['default', 'console'], #
  28. 'level': 'DEBUG',
  29. 'propagate': True, # 向上(更高level的logger)传递
  30. },
  31.  
  32. }
  33.  
  34. #我们的解决方式是,定义一个空的key
  35. 'loggers': {
  36. '': {
  37. 'handlers': ['default', 'console'],
  38. 'level': 'DEBUG',
  39. 'propagate': True,
  40. },
  41.  
  42. }
  43.  
  44. 这样我们再取logger对象时
  45. logging.getLogger(__name__),不同的文件__name__不同,这保证了打印日志时标识信息不同,但是拿着该名字去loggers里找key名时却发现找不到,于是默认使用key=''的配置
  1. 另外一个django的配置,瞄一眼就可以,跟上面的一样

#logging_config.py
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. #logging_config.py
  2. LOGGING = {
  3. 'version': 1,
  4. 'disable_existing_loggers': False,
  5. 'formatters': {
  6. 'standard': {
  7. 'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'
  8. '[%(levelname)s][%(message)s]'
  9. },
  10. 'simple': {
  11. 'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
  12. },
  13. 'collect': {
  14. 'format': '%(message)s'
  15. }
  16. },
  17. 'filters': {
  18. 'require_debug_true': {
  19. '()': 'django.utils.log.RequireDebugTrue',
  20. },
  21. },
  22. 'handlers': {
  23. #打印到终端的日志
  24. 'console': {
  25. 'level': 'DEBUG',
  26. 'filters': ['require_debug_true'],
  27. 'class': 'logging.StreamHandler',
  28. 'formatter': 'simple'
  29. },
  30. #打印到文件的日志,收集info及以上的日志
  31. 'default': {
  32. 'level': 'INFO',
  33. 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
  34. 'filename': os.path.join(BASE_LOG_DIR, "xxx_info.log"), # 日志文件
  35. 'maxBytes': 1024 * 1024 * 5, # 日志大小 5M
  36. 'backupCount': 3,
  37. 'formatter': 'standard',
  38. 'encoding': 'utf-8',
  39. },
  40. #打印到文件的日志:收集错误及以上的日志
  41. 'error': {
  42. 'level': 'ERROR',
  43. 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
  44. 'filename': os.path.join(BASE_LOG_DIR, "xxx_err.log"), # 日志文件
  45. 'maxBytes': 1024 * 1024 * 5, # 日志大小 5M
  46. 'backupCount': 5,
  47. 'formatter': 'standard',
  48. 'encoding': 'utf-8',
  49. },
  50. #打印到文件的日志
  51. 'collect': {
  52. 'level': 'INFO',
  53. 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
  54. 'filename': os.path.join(BASE_LOG_DIR, "xxx_collect.log"),
  55. 'maxBytes': 1024 * 1024 * 5, # 日志大小 5M
  56. 'backupCount': 5,
  57. 'formatter': 'collect',
  58. 'encoding': "utf-8"
  59. }
  60. },
  61. 'loggers': {
  62. #logging.getLogger(__name__)拿到的logger配置
  63. '': {
  64. 'handlers': ['default', 'console', 'error'],
  65. 'level': 'DEBUG',
  66. 'propagate': True,
  67. },
  68. #logging.getLogger('collect')拿到的logger配置
  69. 'collect': {
  70. 'handlers': ['console', 'collect'],
  71. 'level': 'INFO',
  72. }
  73. },
  74. }
  75.  
  76. # -----------
  77. # 用法:拿到俩个logger
  78.  
  79. logger = logging.getLogger(__name__) #线上正常的日志
  80. collect_logger = logging.getLogger("collect") #领导说,需要为领导们单独定制领导们看的日志

十二 logging模块的更多相关文章

  1. Python进阶(十二)----re模块

    Python进阶(十二)----re模块 一丶re模块 ​ re模块是python将正则表达式封装之后的一个模块.正则表达式模式被编译成一系列的字节码,然后由用C编写的匹配引擎执行. #正则表达式: ...

  2. 常见模块(二) logging模块

    logging模块是专门做日志系统的.分为函数版和自定义函数. (一)logging模块初级版 缺点,不能指定字符集,不能把屏幕输出和文件日志同时记录.只能选择其一. 文件记录日志 import lo ...

  3. 22、手把手教你Extjs5(二十二)模块Form的自定义的设计[1]

    下面开始设计和完成一个简单的Form的自定义过程.先准备数据,在ModuleModel.js中的data属性下面,加入自定义Form的参数定义,下面的代码中定义了一个新的属性tf_formScheme ...

  4. 第十二、模块二、调用中国天气网和qqOnline及TrainTimeWebService接口来突出Json方法

    一. 浏览网页的时候,发送的请求.服务器反回来的永远是字符串,由于服务器后台使用的语言不通,所以就需要用工具反解,这里用到了json json方法一 json.loads()将字符串转化为python ...

  5. python学习(十二)模块

    怎么一下子就来学了模块? 其实学了判断.循环.函数等知识就可以开始下水写程序了,不用在意其他的细节,等你用到的时候再回过头去看,此所谓囫囵吞枣学习法. 为啥学模块? 有点用的.或者有点规模的程序都是要 ...

  6. Python3简明教程(十二)—— 模块

    在这节我们将要学习 Python 模块相关知识.包括模块的概念和导入方法,包的概念和使用,第三方模块的介绍,命令行参数的使用等. 模块 到目前为止,我们在 Python 解释器中写的所有代码都在我们退 ...

  7. python基础(十二)--模块

    模块的导入方式 import os  调用时os.rename from os import rename #只导入的特定功能 调用时rename() from asynico.events impo ...

  8. 【Python】学习笔记十二:模块

    模块(module) 在Python中,一个.py文件就是一个模块.通过模块,你可以调用其它文件中的程序 引入模块 先写一个first.py文件,内容如下: def letter(): print(' ...

  9. 异常处理--logging模块

    一. 异常处理 1. 异常类型: 语法错误 : 空格 缩进 语法规则 应该在我们写代码的时候就避免 逻辑错误: 应该在程序当中写代码处理 条件判断 异常处理 2. 常见的报错类型: Attribute ...

随机推荐

  1. Map集合、HashMap集合、LinkedHashMap集合、Hashtable集合、Collections工具类和模拟斗地主洗牌和发牌

    1.Map集合概述和特点 * A:Map接口概述  * 查看API可以知道:          * 将键映射到值的对象          * 一个映射不能包含重复的键          * 每个键最多 ...

  2. 互联网媒体类型 MIME Type

    参考:https://zh.wikipedia.org/wiki/%E4%BA%92%E8%81%94%E7%BD%91%E5%AA%92%E4%BD%93%E7%B1%BB%E5%9E%8B 互联网 ...

  3. 我发起并创立了一个 C 语言编译器 开源项目 InnerC

    本文是 VMBC / D#  项目 的 系列文章, 有关 VMBC / D# ,  见 <我发起并创立了一个 VMBC 的 子项目 D#>(以下简称 <D#>)  https: ...

  4. ssh 22端口号拒绝

    1:当scp或者ssh登录ubuntu远程服务的时候,出现:

  5. cpgf如何实现lua script binding的?

    Lib: https://github.com/cpgf/cpgf/tree/master 代码 以下是operator的实现函数 int UserData_operator(lua_State * ...

  6. CentOS7 上学习使用docker

    一.CentOS7(64)上安装和使用docker的笔记. 1. 增加docker用户 sudo groupadd docker sudo useradd -g docker docker 2. 增加 ...

  7. SpringBoot Web开发(5) 开发页面国际化+登录拦截

    SpringBoot Web开发(5) 开发页面国际化+登录拦截 一.页面国际化 页面国际化目的:根据浏览器语言设置的信息对页面信息进行切换,或者用户点击链接自行对页面语言信息进行切换. **效果演示 ...

  8. 关于Spring的那点事

    一.Spring约束 <?xml version="1.0" encoding="UTF-8"?><beans xmlns="htt ...

  9. SpringSecurity-UsernamePasswordAuthenticationFilter的作用

    UsernamePasswordAuthenticationFilter应该是我们最关注的Filter,因为它实现了我们最常用的基于用户名和密码的认证逻辑. 先看一下一个常用的form-login配置 ...

  10. sqlserver存储过程sp_send_dbmail邮件(html)实际应用

    前段时间因工作需求,特地学习了下sp_send_dbmail的使用,发现网上的示例对我这样的菜鸟太不友好/(ㄒoㄒ)/~~,好不容易完工来和大家分享一下,不谈理论,只管实践! 如下是实际需求: -- ...