我想使用dictConfig,但文档有点抽象。在哪里可以找到与dictConfig
一起使用的字典的具体复制+粘贴示例?
答案 0 :(得分:144)
这里怎么样!
{
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
},
},
'handlers': {
'default': {
'level': 'INFO',
'formatter': 'standard',
'class': 'logging.StreamHandler',
'stream': 'ext://sys.stdout', # Default is stderr
},
},
'loggers': {
'': { # root logger
'handlers': ['default'],
'level': 'INFO',
'propagate': True
},
'my.packg': {
'handlers': ['default'],
'level': 'WARN',
'propagate': False
},
}
}
答案 1 :(得分:27)
接受的答案很好!但如果一个人可以从不那么复杂的事情开始呢?日志模块是非常强大的东西,文档有点压倒性,特别是对于新手。但是一开始你不需要配置格式化程序和处理程序。你可以在弄清楚自己想要的东西时添加它。
例如:
import logging.config
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'loggers': {
'': {
'level': 'INFO',
},
'another.module': {
'level': 'DEBUG',
},
}
}
logging.config.dictConfig(DEFAULT_LOGGING)
logging.info('Hello, log')
答案 2 :(得分:2)
我在下面找到了Django v1.11.15的默认配置,希望对您有帮助
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse',
},
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'formatters': {
'django.server': {
'()': 'django.utils.log.ServerFormatter',
'format': '[%(server_time)s] %(message)s',
}
},
'handlers': {
'console': {
'level': 'INFO',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
},
'django.server': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'django.server',
},
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django': {
'handlers': ['console', 'mail_admins'],
'level': 'INFO',
},
'django.server': {
'handlers': ['django.server'],
'level': 'INFO',
'propagate': False,
},
}
}
答案 3 :(得分:1)
有一个更新的示例,声明了一个隐藏在 dictionary schema 中的 logging.config.dictConfig() logging cookbook examples。从该食谱链接向上滚动以查看 dictConfig() 的用法。
以下是使用 StreamHandler 和带有自定义 RotatingFileHandler
和 format
的 datefmt
记录到 stdout 和“logs”子目录的示例用例。
导入模块并建立到“logs”子目录的跨平台绝对路径
from os.path import abspath, dirname, join
import logging
from logging.config import dictConfig
base_dir = abspath(dirname(__file__))
logs_target = join(base_dir + "\logs", "python_logs.log")
根据 dictionary schema 文档建立架构。
logging_schema = {
# Always 1. Schema versioning may be added in a future release of logging
"version": 1,
# "Name of formatter" : {Formatter Config Dict}
"formatters": {
# Formatter Name
"standard": {
# class is always "logging.Formatter"
"class": "logging.Formatter",
# Optional: logging output format
"format": "%(asctime)s\t%(levelname)s\t%(filename)s\t%(message)s",
# Optional: asctime format
"datefmt": "%d %b %y %H:%M:%S"
}
},
# Handlers use the formatter names declared above
"handlers": {
# Name of handler
"console": {
# The class of logger. A mixture of logging.config.dictConfig() and
# logger class-specific keyword arguments (kwargs) are passed in here.
"class": "logging.StreamHandler",
# This is the formatter name declared above
"formatter": "standard",
"level": "INFO",
# The default is stderr
"stream": "ext://sys.stdout"
},
# Same as the StreamHandler example above, but with different
# handler-specific kwargs.
"file": {
"class": "logging.handlers.RotatingFileHandler",
"formatter": "standard",
"level": "INFO",
"filename": logs_target,
"mode": "a",
"encoding": "utf-8",
"maxBytes": 500000,
"backupCount": 4
}
},
# Loggers use the handler names declared above
"loggers" : {
"__main__": { # if __name__ == "__main__"
# Use a list even if one handler is used
"handlers": ["console", "file"],
"level": "INFO",
"propagate": False
}
},
# Just a standalone kwarg for the root logger
"root" : {
"level": "INFO",
"handlers": ["file"]
}
}
使用字典架构配置 logging
dictConfig(logging_schema)
尝试一些测试用例,看看是否一切正常
if __name__ == "__main__":
logging.info("testing an info log entry")
logging.warning("testing a warning log entry")
答案 4 :(得分:0)
具有流处理程序,文件处理程序,旋转文件处理程序和SMTP处理程序的示例
from logging.config import dictConfig
LOGGING_CONFIG = {
'version': 1,
'loggers': {
'': { # root logger
'level': 'NOTSET',
'handlers': ['debug_console_handler', 'info_rotating_file_handler', 'error_file_handler', 'critical_mail_handler'],
},
'my.package': {
'level': 'WARNING',
'propagate': False,
'handlers': ['info_rotating_file_handler', 'error_file_handler' ]
},
'handlers': {
'debug_console_handler': {
'level': 'DEBUG',
'formatter': 'info',
'class': 'logging.StreamHandler',
'stream': 'ext://sys.stdout',
},
'info_rotating_file_handler': {
'level': 'INFO',
'formatter': 'info',
'class': 'logging.handlers.RotatingFileHandler',
'filename': 'info.log',
'mode': 'a',
'maxBytes': 1048576,
'backupCount': 10
},
'error_file_handler': {
'level': 'WARNING',
'formatter': 'error',
'class': 'logging.FileHandler',
'filename': 'error.log',
'mode': 'a',
},
'critical_mail_handler': {
'level': 'CRITICAL',
'formatter': 'error',
'class': 'logging.handlers.SMTPHandler',
'mailhost' : 'localhost',
'fromaddr': 'monitoring@domain.com',
'toaddrs': ['dev@domain.com', 'qa@domain.com'],
'subject': 'Critical error with application name'
}
},
'formatters': {
'info': {
'format': '%(asctime)s-%(levelname)s-%(name)s::%(module)s|%(lineno)s:: %(message)s'
},
'error': {
'format': '%(asctime)s-%(levelname)s-%(name)s-%(process)d::%(module)s|%(lineno)s:: %(message)s'
},
},
}
dictConfig(LOGGING_CONFIG)
答案 5 :(得分:-5)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import logging.handlers
from logging.config import dictConfig
logger = logging.getLogger(__name__)
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
}
def configure_logging(logfile_path):
"""
Initialize logging defaults for Project.
:param logfile_path: logfile used to the logfile
:type logfile_path: string
This function does:
- Assign INFO and DEBUG level to logger file handler and console handler
"""
dictConfig(DEFAULT_LOGGING)
default_formatter = logging.Formatter(
"[%(asctime)s] [%(levelname)s] [%(name)s] [%(funcName)s():%(lineno)s] [PID:%(process)d TID:%(thread)d] %(message)s",
"%d/%m/%Y %H:%M:%S")
file_handler = logging.handlers.RotatingFileHandler(logfile_path, maxBytes=10485760,backupCount=300, encoding='utf-8')
file_handler.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(default_formatter)
console_handler.setFormatter(default_formatter)
logging.root.setLevel(logging.DEBUG)
logging.root.addHandler(file_handler)
logging.root.addHandler(console_handler)
[31/10/2015 22:00:33] [DEBUG] [yourmodulename] [yourfunction_name():9] [PID:61314 TID:140735248744448] this is logger infomation from hello module