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。

python 多进程 logging:ConcurrentLogHandler的更多相关文章

  1. Python 中 logging 日志模块在多进程环境下的使用

    因为我的个人网站 restran.net 已经启用,博客园的内容已经不再更新.请访问我的个人网站获取这篇文章的最新内容,Python 中 logging 日志模块在多进程环境下的使用 使用 Pytho ...

  2. Python多进程multiprocessing使用示例

    mutilprocess简介 像线程一样管理进程,这个是mutilprocess的核心,他与threading很是相像,对多核CPU的利用率会比threading好的多. import multipr ...

  3. Python多进程池 multiprocessing Pool

    1. 背景 由于需要写python程序, 定时.大量发送htttp请求,并对结果进行处理. 参考其他代码有进程池,记录一下. 2. 多进程 vs 多线程 c++程序中,单个模块通常是单进程,会启动几十 ...

  4. Python 多进程教程

    Python2.6版本中新添了multiprocessing模块.它最初由Jesse Noller和Richard Oudkerk定义在PEP 371中.就像你能通过threading模块衍生线程一样 ...

  5. Python多进程库multiprocessing创建进程以及进程池Pool类的使用

    问题起因最近要将一个文本分割成好几个topic,每个topic设计一个regressor,各regressor是相互独立的,最后汇总所有topic的regressor得到总得预测结果.没错!类似bag ...

  6. Python之logging模块

    一.引言 之前在写一些小程序的时候想把日志内容打到文件中,所以就自己写了一个logger.py的程序,如下: #!/usr/bin/python # -*- coding=utf-8 -*- impo ...

  7. Python多进程编程

    转自:Python多进程编程 阅读目录 1. Process 2. Lock 3. Semaphore 4. Event 5. Queue 6. Pipe 7. Pool 序. multiproces ...

  8. Python多进程(1)——subprocess与Popen()

    Python多进程方面涉及的模块主要包括: subprocess:可以在当前程序中执行其他程序或命令: mmap:提供一种基于内存的进程间通信机制: multiprocessing:提供支持多处理器技 ...

  9. Python多进程使用

    [Python之旅]第六篇(六):Python多进程使用   香飘叶子 2016-05-10 10:57:50 浏览190 评论0 python 多进程 多进程通信 摘要:   关于进程与线程的对比, ...

随机推荐

  1. bzoj 3679: 数字之积

    Description 一个数x各个数位上的数之积记为\(f(x)\) 求[L,R)中满足\(0<f(x)<=n\)的数的个数 solution 最后\(f(x)\)可以拆分成2,3,5, ...

  2. hdu 5428

    题意:一个数是这n个数的乘,找出它一个不是素数的最小因子 求出所有数的所有质因子中最小的两个,相乘就是答案.如果所有数字的质因子个数不到两个,那么就是无解. #include<iostream& ...

  3. 习题9-6 uva 10723

    题意: 给你两个字符串,求一个最短的串,使得输入的两个串均是他的子序列(不一定连续) 思路: 可以看出ans = 两个串的长度和 - 两个串的最长公共子序列,在最后的构造处GG.  在构造时想了很久, ...

  4. bzoj2655calc 容斥+dp

    2655: calc Time Limit: 30 Sec  Memory Limit: 512 MBSubmit: 322  Solved: 197[Submit][Status][Discuss] ...

  5. seq2seq-chatbot:200 行代码实现聊天机器人

    Chatbot in 200 lines of code CPU 跑不动 github:https://github.com/zsdonghao/seq2seq-chatbot 更多英文,中文聊天机器 ...

  6. 一个使用 Python 的人工智能聊天机器人框架

    一个Python 的 AI Chatbot框架 建立一个聊天室可以听起来很棒,但它是完全可行的. IKY是一个内置于Python中的AI动力对话对话界面. 使用IKY,很容易创建自然语言会话场景,无需 ...

  7. Linux学习之CentOS(四)----Linux文件属性、所有者、群组、其他组及文件权限操作简要总结

    Linux文件属性.所有者.群组.其他组及文件权限操作简要总结 首先介绍一个重要的知识点:文件属性控制权限 [root@www ~]# ls -al total 156 drwxr-x--- 4 ro ...

  8. Docker学习系列(一)Docker简介

    简介 Docker是一个在全球范围领先的软件容器平台.开发人员可以使用容器来在协作过程中遇到的解决"不同环境配置"的问题.(例如,在传统的开发环境下,开发人员编写代码,然后交由测试 ...

  9. 继承自 DevExpress 17.2 的自定义控件如何在工具箱显示

    最近把DevExpress版本从13.1升级到了17.2,结果发现继承自DevExpress的自定义控件居然在工具箱中消失了,弄了两天还是没有任何头绪,部分自定义Dev控件可以正常出现,但大部分自定义 ...

  10. ubuntu15.10 安装 virtualbox5.0

    首先安装依赖包.ubuntu15.01安装的时候会出现这个错误: virtualbox-); however: Package libvpx1 is not installed 而且sudo apt- ...