python 多进程 logging:ConcurrentLogHandler

python 多进程 logging:ConcurrentLogHandler

python的logging模块RotatingFileHandler仅仅是线程安全的,如果多进程多线程使用,推荐 ConcurrentLogHandler. 安装之:

# Using ConcurrentLogHandler:

# wget https://pypi.python.org/packages/fd/e5/0dc4f256bcc6484d454006b02f33263b20f762a433741b29d53875e0d763/ConcurrentLogHandler-0.9.1.tar.gz#md5=9609ecc4c269ac43f0837d89f12554c3
# cd ConcurrentLogHandler-0.9.1
# python2.7 setup.py install

Linux下建一个目录,下面的文件都放到这个目录中:

1) logging-config.ini

[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

2) logging-config.yaml

version: 1

formatters:
    simple:
        format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'

handlers:
    console:
        class: logging.StreamHandler
        level: DEBUG
        formatter: simple
        stream: ext://sys.stdout

loggers:
    simpleExample:
        level: DEBUG
        handlers: [console]
        propagate: no

root:
    level: DEBUG
    handlers: [console]

3) testlogging.py

#!/usr/bin/python2.7
#-*- coding: UTF-8 -*-
#
# Using ConcurrentLogHandler:
#   wget https://pypi.python.org/packages/fd/e5/0dc4f256bcc6484d454006b02f33263b20f762a433741b29d53875e0d763/ConcurrentLogHandler-0.9.1.tar.gz#md5=9609ecc4c269ac43f0837d89f12554c3
#   cd ConcurrentLogHandler-0.9.1
#   python2.7 setup.py install
###########################################################
import logging, logging.config
import cloghandler

import yaml

###########################################################
# create logger
# 使用代码创建logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')


###########################################################
# basicConfig
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')


###########################################################
# using yaml config file
f = open("logging-config.yaml")
dictcfg = yaml.load(f)
f.close()

logging.config.dictConfig(dictcfg)

#logging.config.fileConfig("logging.config")
log = logging.getLogger("root")
log.info("==YAML== Here is a very exciting log message")

###########################################################
# using ini config file
logging.config.fileConfig("logging-config.ini")
log = logging.getLogger("simpleExample")
log.info("==INI== Here is a very exciting log message")


###########################################################
# using inline code config
logging.config.dictConfig({
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt': "%Y-%m-%d %H:%M:%S",
        },
        'simple': {
            'format': '%(levelname)s %(message)s',
        },
    },
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'logging.NullHandler',
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
        'file': {
            'level': 'DEBUG',
            'class': 'cloghandler.ConcurrentRotatingFileHandler',
            'maxBytes': 1024 * 1024 * 10,   # 当达到10MB时分割日志
            'backupCount': 10,              # 最多保留10份文件
            'delay': True,                  # If delay is true, file opening is deferred until the first call to emit
            'filename': 'sample-site.log',
            'formatter': 'verbose',
        },
        'file2': {
            'level': 'DEBUG',
            'class': 'cloghandler.ConcurrentRotatingFileHandler',
            'maxBytes': 1024 * 1024 * 10,   # 当达到10MB时分割日志
            'backupCount': 10,              # 最多保留10份文件
            'delay': True,                  # If delay is true, file opening is deferred until the first call to emit
            'filename': 'sample-site2.log',
            'formatter': 'verbose',
        },
    },
    'loggers': {
        '': {
            'handlers': ['file'],
            'level': 'INFO',
        },
        'root': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': 0,
        },
        'root2': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': 1,
        },
    },
})

logger = logging.getLogger("root")
logger.info("==== Here is a very exciting log message")

logger = logging.getLogger("root2")
logger.info("==== Here is a very exciting log message2")

至于喜欢使用哪种配置(ini, yaml还是代码)看自己喜欢了。我建议是yaml。


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Python中,可以使用`multiprocessing`模块创建多个进程来并行执行任务。当多个进程同时执行时,由于每个进程都有自己的执行环境,因此它们的日志信息需要分别记录。为了实现多进程的日志记录,可以使用`multiprocessing`模块的`Queue`来处理日志信息的传递。 首先,我们可以在主进程中创建一个`Queue`对象,用于接收各个子进程的日志信息。然后,将这个`Queue`对象作为参数传递给每个子进程,在子进程中通过`logging`模块将日志信息发送到这个`Queue`中。主进程可以通过不断从`Queue`中获取日志信息并进行记录。 具体实现代码如下: ```python import logging import multiprocessing from multiprocessing import Queue # 配置logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(processName)s %(message)s') # 获取日志队列 def get_logger(queue): # 配置logger logger = logging.getLogger() logger.setLevel(logging.INFO) # 设置Handler handler = logging.QueueHandler(queue) logger.addHandler(handler) # 日志输出到控制台 console = logging.StreamHandler() console.setLevel(logging.INFO) logger.addHandler(console) logger.info('sub process started.') if __name__ == '__main__': # 创建日志队列 queue = Queue() # 创建子进程 p = multiprocessing.Process(target=get_logger, args=(queue,)) p.start() # 创建主进程的logger logger = logging.getLogger() logger.setLevel(logging.INFO) handler = logging.StreamHandler() handler.setLevel(logging.INFO) logger.addHandler(handler) # 主进程等待并获取日志信息进行记录 while True: try: record = queue.get(timeout=1) logger.handle(record) except Exception as e: break logger.info('all sub processes finished.') ``` 通过这种方式,可以实现多个子进程并行执行任务,并且可以记录每个子进程的日志信息,方便日志的统一管理和分析。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

车斗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值