Python:记录模块 - 全局 [英] Python: logging module - globally

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

问题描述

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



我有

  class customLogger(logging.Logger):
...

放在一个带格式化器和其他东西的文件中。
这个记录器可以自己完美地工作。



我在main.py文件中导入这个模块并创建一个像这样的对象:

  self.log = log.customLogger(arguments)

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

使用 logging.getLogger(name) 创建一个指定的全局记录器。 p>

main.py

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

导入子模块

log.py

 导入日志

def setup_custom_logger(name):
formatter = logging.Formatter(fmt ='%(asctime)s - %(levelname)s - %( ())
$ b $ handler = logging.StreamHandler()名称)
logger.setLevel(logging.DEBUG)
logger.addHandler(处理程序)
返回记录程序

子模块.py

 导入日志记录

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

输出

  2011-10-01 20:08:40,049  -  DEBUG  -  main  - 主要信息
2011 -10-01 20:08:40,050 - DEBUG - 子模块 - 子模块消息


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

I have

class customLogger(logging.Logger):
   ...

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

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

self.log = log.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?

解决方案

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

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

Output

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天全站免登陆