Python:日志模块 - 全局 [英] Python: logging module - globally

查看:31
本文介绍了Python:日志模块 - 全局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何实现一个可以在任何地方使用您自己的设置的全局记录器:

I was wondering how to implement a global logger that could be used everywhere with your own settings:

我目前有一个自定义记录器类:

I currently have a custom logger class:

class customLogger(logging.Logger):
   ...

该类位于一个单独的文件中,其中包含一些格式化程序和其他内容.记录器可以自行完美运行.

The class is in a separate file with some formatters and other stuff. The logger works perfectly on its own.

我在我的主 python 文件中导入这个模块并创建一个这样的对象:

I import this module in my main python file and create an object like this:

self.log = logModule.customLogger(arguments)

但显然,我无法从代码的其他部分访问此对象.我使用了错误的方法吗?有没有更好的方法来做到这一点?

But obviously, I cannot access this object from other parts of my code. Am i using a wrong approach? Is there a better way to do this?

推荐答案

使用 logging.getLogger(name) 创建一个命名的全局记录器.

Use logging.getLogger(name) to create a named global logger.

ma​​in.py

import log
logger = log.setup_custom_logger('root')
logger.debug('main message')

import submodule

log.py

import logging

def setup_custom_logger(name):
    formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s')

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

    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)
    return logger

submodule.py

import logging

logger = logging.getLogger('root')
logger.debug('submodule message')

输出

2011-10-01 20:08:40,049 - DEBUG - main - main message
2011-10-01 20:08:40,050 - DEBUG - submodule - submodule message

这篇关于Python:日志模块 - 全局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆