python大型项目中的日志模块_如何在多个模块中使用python日志记录

I was wondering what the standard set up is for performing logging from within a Python app.

I am using the Logging class, and I've written my own logger class that instantiates the Logging class. My main then instantiates my logger wrapper class. However, my main instantiates other classes and I want those other classes to also be able to write to he log file via the logger object in the main.

How do I make that logger object such that it can be called by other classes? It's almost like we need some sort of static logger object to get this to work.

I guess the long and short of the question is: how do you implement logging within your code structure such that all classes instantiated from within main can write to the same log file? Do I just have to create a new logging object in each of the classes that points to the same file?

解决方案

I don't know what you mean by the Logging class - there's no such class in Python's built-in logging. You don't really need wrappers: here's an example of how to do logging from arbitrary classes that you write:

import logging

# This class could be imported from a utility module

class LogMixin(object):

@property

def logger(self):

name = '.'.join([__name__, self.__class__.__name__])

return logging.getLogger(name)

# This class is just there to show that you can use a mixin like LogMixin

class Base(object):

pass

# This could be in a module separate from B

class A(Base, LogMixin):

def __init__(self):

# Example of logging from a method in one of your classes

self.logger.debug('Hello from A')

# This could be in a module separate from A

class B(Base, LogMixin):

def __init__(self):

# Another example of logging from a method in one of your classes

self.logger.debug('Hello from B')

def main():

# Do some work to exercise logging

a = A()

b = B()

with open('myapp.log') as f:

print('Log file contents:')

print(f.read())

if __name__ == '__main__':

# Configure only in your main program clause

logging.basicConfig(level=logging.DEBUG,

filename='myapp.log', filemode='w',

format='%(name)s %(levelname)s %(message)s')

main()

Generally it's not necessary to have loggers at class level: in Python, unlike say Java, the unit of program (de)composition is the module. However, nothing stops you from doing it, as I've shown above. The script, when run, displays:

Log file contents:

__main__.A DEBUG Hello from A

__main__.B DEBUG Hello from B

Note that code from both classes logged to the same file, myapp.log. This would have worked even with A and B in different modules.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值