哪里有logging.config.dictConfig的完整示例?

发布于 2024-12-05 14:06:29 字数 176 浏览 0 评论 0 原文

如何使用 dictConfig?我应该如何指定其输入config字典?

How do I use dictConfig? How should I specify its input config dictionary?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

淡写薰衣草的香 2024-12-12 14:06:30

有一个声明logging.config.dictConfig() 字典模式埋藏在记录食谱示例。从该食谱链接向上滚动以查看 dictConfig() 的用法。

以下是使用 StreamHandler 和 RotatingFileHandler 带有自定义的 格式datefmt

  1. 导入模块并建立“logs”子目录的跨平台绝对路径

    from os.path import abspath, dirname, join
    导入日志记录
    从logging.config导入dictConfig
    base_dir = 绝对路径(目录名(__file__))
    logs_target = join(base_dir + "\logs", "python_logs.log")
    
  2. 根据字典架构文档。

    logging_schema = {
        # 始终 1. 未来版本的日志记录中可能会添加架构版本控制
        “版本”:1,
        # "格式化程序名称" : {Formatter Config Dict}
        “格式化程序”:{
            # 格式化程序名称
            “标准”: {
                # 类始终是“logging.Formatter”
                "class": "logging.Formatter",
                # 可选:日志输出格式
                "format": "%(asctime)s\t%(levelname)s\t%(文件名)s\t%(message)s",
                # 可选:asctime 格式
                "datefmt": "%d %b %y %H:%M:%S"
            }
        },
        # 处理程序使用上面声明的格式化程序名称
        “处理程序”:{
            # 处理程序名称
            “安慰”: {
                # 记录器类。混合了logging.config.dictConfig()和
                # 记录器类特定的关键字参数 (kwargs) 在这里传递。 
                "class": "logging.StreamHandler",
                # 这是上面声明的格式化程序名称
                “格式化程序”:“标准”,
                “级别”:“信息”,
                # 默认是stderr
                “流”:“ext://sys.stdout”
            },
            # 与上面的 StreamHandler 示例相同,但不同
            # 处理程序特定的 kwargs。
            “文件”: {  
                "class": "logging.handlers.RotatingFileHandler",
                “格式化程序”:“标准”,
                “级别”:“信息”,
                “文件名”:logs_target,
                “模式”:“a”,
                “编码”:“utf-8”,
                “最大字节数”:500000,
                “备份计数”:4
            }
        },
        # 记录器使用上面声明的处理程序名称
        “记录器”:{
            "__main__": { # if __name__ == "__main__"
                # 即使使用一个处理程序也使用列表
                “处理程序”:[“控制台”,“文件”],
                “级别”:“信息”,
                “传播”:错误
            }
        },
        # 只是根记录器的独立 kwarg
        “根” : {
            “级别”:“信息”,
            “处理程序”:[“文件”]
        }
    }
    
  3. 使用字典架构配置日志记录

    dictConfig(logging_schema)
    
  4. 尝试一些测试用例以查看一切是否正常工作

    如果 __name__ == "__main__":
        logging.info(“测试信息日志条目”)
        logging.warning(“测试警告日志条目”)
    

[编辑回答@baxx的问题]

  1. 要在代码库中重用此设置,请在调用 dictConfig() 的脚本中实例化记录器,然后将该记录器导入其他地方

     # my_module/config/my_config.py
     dictConfig(logging_schema)
     my_logger = getLogger(__name__)
    

然后在另一个脚本中

    from my_module.config.my_config import my_logger as logger
    logger.info("Hello world!")

There's an updated example of declaring a logging.config.dictConfig() dictionary schema buried in the logging cookbook examples. Scroll up from that cookbook link to see a use of dictConfig().

Here's an example use case for logging to both stdout and a "logs" subdirectory using a StreamHandler and RotatingFileHandler with customized format and datefmt.

  1. Imports modules and establish a cross-platform absolute path to the "logs" subdirectory

    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")
    
  2. Establish the schema according to the dictionary schema documentation.

    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"]
        }
    }
    
  3. Configure logging with the dictionary schema

    dictConfig(logging_schema)
    
  4. Try some test cases to see if everything is working properly

    if __name__ == "__main__":
        logging.info("testing an info log entry")
        logging.warning("testing a warning log entry")
    

[EDIT to answer @baxx's question]

  1. To reuse this setting across your code base, instantiate a logger in the script you call dictConfig() and then import that logger elsewhere

     # my_module/config/my_config.py
     dictConfig(logging_schema)
     my_logger = getLogger(__name__)
    

Then in another script

    from my_module.config.my_config import my_logger as logger
    logger.info("Hello world!")
无法回应 2024-12-12 14:06:30

我发现 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,
        },
    }
}

I found Django v1.11.15 default config below, hope it helps

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,
        },
    }
}
南巷近海 2024-12-12 14:06:30

另一件事是,如果从现有记录器的配置开始很有用,则可以通过以下方式获取当前的配置字典

import logging
logger = logging.getLogger()
current_config = logger.__dict__  # <-- yes, it's just the dict

print(current_config)  

{'filters': [], 'name': 'root', 'level': 30, 'parent': None, 'propagate': True, 'handlers': [], 'disabled': False, '_cache': {}}

然后,如果您这样做,

new_config=current_config

new_config['version']=1
new_config['name']='fubar'
new_config['level']=20
#  ...and whatever other changes you wish

logging.config.dictConfig(new_config)

您将发现:

print(logger.__dict__)

是您所希望的

{'filters': [], 'name': 'fubar', 'level': 20, 'parent': None, 'propagate': True, 'handlers': [], 'disabled': False, '_cache': {}, 'version': 1}

One more thing in case it's useful to start from the existing logger's config, the current config dictionary is can be obtained via

import logging
logger = logging.getLogger()
current_config = logger.__dict__  # <-- yes, it's just the dict

print(current_config)  

It'll be something like:

{'filters': [], 'name': 'root', 'level': 30, 'parent': None, 'propagate': True, 'handlers': [], 'disabled': False, '_cache': {}}

Then, if you just do

new_config=current_config

new_config['version']=1
new_config['name']='fubar'
new_config['level']=20
#  ...and whatever other changes you wish

logging.config.dictConfig(new_config)

You will then find:

print(logger.__dict__)

is what you'd hope for

{'filters': [], 'name': 'fubar', 'level': 20, 'parent': None, 'propagate': True, 'handlers': [], 'disabled': False, '_cache': {}, 'version': 1}
衣神在巴黎 2024-12-12 14:06:29

这里怎么样!相应的文档参考是 configuration-dictionary-schema

LOGGING_CONFIG = { 
    'version': 1,
    'disable_existing_loggers': True,
    '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': 'WARNING',
            'propagate': False
        },
        'my.packg': { 
            'handlers': ['default'],
            'level': 'INFO',
            'propagate': False
        },
        '__main__': {  # if __name__ == '__main__'
            'handlers': ['default'],
            'level': 'DEBUG',
            'propagate': False
        },
    } 
}

用法:

import logging.config

# Run once at startup:
logging.config.dictConfig(LOGGING_CONFIG)

# Include in each module:
log = logging.getLogger(__name__)
log.debug("Logging is configured.")

如果您看到来自第三方软件包的日志过多,请务必在第三方软件包之前使用 logging.config.dictConfig(LOGGING_CONFIG) 运行此配置是进口的。

要使用日志过滤器向每条日志消息添加其他自定义信息,请考虑此答案

How about here! The corresponding documentation reference is configuration-dictionary-schema.

LOGGING_CONFIG = { 
    'version': 1,
    'disable_existing_loggers': True,
    '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': 'WARNING',
            'propagate': False
        },
        'my.packg': { 
            'handlers': ['default'],
            'level': 'INFO',
            'propagate': False
        },
        '__main__': {  # if __name__ == '__main__'
            'handlers': ['default'],
            'level': 'DEBUG',
            'propagate': False
        },
    } 
}

Usage:

import logging.config

# Run once at startup:
logging.config.dictConfig(LOGGING_CONFIG)

# Include in each module:
log = logging.getLogger(__name__)
log.debug("Logging is configured.")

In case you see too many logs from third-party packages, be sure to run this config using logging.config.dictConfig(LOGGING_CONFIG) before the third-party packages are imported.

To add additional custom info to each log message using a logging filter, consider this answer.

千鲤 2024-12-12 14:06:29

接受的答案很好!但如果可以从不太复杂的事情开始呢?日志记录模块非常强大,而且文档有点让人不知所措,尤其是对于新手来说。但一开始,您不需要配置格式化程序和处理程序。当你弄清楚你想要什么时,你可以添加它。

例如:

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')

The accepted answer is nice! But what if one could begin with something less complex? The logging module is very powerful thing and the documentation is kind of a little bit overwhelming especially for novice. But for the beginning you don't need to configure formatters and handlers. You can add it when you figure out what you want.

For example:

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')
︶ ̄淡然 2024-12-12 14:06:29

流处理程序、文件处理程序、旋转文件处理程序和 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': '[email protected]',
            'toaddrs': ['[email protected]', '[email protected]'],
            '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)

Example with Stream Handler, File Handler, Rotating File Handler and SMTP Handler

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': '[email protected]',
            'toaddrs': ['[email protected]', '[email protected]'],
            '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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文