python日志记录对象日志仅在_init_方法

时间:2018-01-20 12:58:34

标签: python logging

在这里尝试使用python deamon类中的日志记录是父deamon类和派生类

import sys, os, time, atexit, signal
import logging.handlers

logger = logging.getLogger(__name__)
fh = logging.handlers.RotatingFileHandler('./logs/application.log', maxBytes=10240, backupCount=5)
fh.setLevel(logging.INFO)  # no matter what level I set here
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)

class Deamon:
    """A generic daemon class.

    Usage: subclass the daemon class and override the run() method."""

    def __init__(self, pidfile):
        self.pidfile = pidfile
        logger.info('INFO')
        logger.error('ERROR')
    def daemonize(self):
        """Deamonize class. UNIX double fork mechanism."""
        try:
            pid = os.fork()
            if pid > 0:
                # exit first parent
                sys.exit(0)
        except OSError as err:
            logger.error('We have a problem')
            sys.stderr.write('fork #1 failed: {0}\n'.format(err))
            sys.exit(1)

        # decouple from parent environment
        os.chdir('/')
        os.setsid()
        os.umask(0)

        # do second fork
        try:
            pid = os.fork()
            if pid > 0:
                # exit from second parent
                sys.exit(0)
        except OSError as err:
            sys.stderr.write('fork #2 failed: {0}\n'.format(err))
            sys.exit(1)

        # redirect standard file descriptors
        sys.stdout.flush()
        sys.stderr.flush()
        si = open(os.devnull, 'r')
        so = open(os.devnull, 'a+')
        se = open(os.devnull, 'a+')

        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())

        # write pidfile
        atexit.register(self.delpid)

        pid = str(os.getpid())
        with open(self.pidfile, 'w+') as f:
            f.write(pid + '\n')

    def delpid(self):
        os.remove(self.pidfile)

    def start(self):
        """Start the daemon."""
        logger.info('start the deamon')
        # Check for a pidfile to see if the daemon already runs
        try:
            with open(self.pidfile, 'r') as pf:
                pid = int(pf.read().strip())
        except IOError:
            pid = None

        if pid:
            message = "pidfile {0} already exist. " + \
                      "Daemon already running?\n"
            sys.stderr.write(message.format(self.pidfile))
            sys.exit(1)

        # Start the daemon
        self.daemonize()
        self.run()

衍生的:

#!/usr/bin/env python

import sys, time
from Deamon import Deamon
import logging.handlers

logger = logging.getLogger(__name__)
fh = logging.handlers.RotatingFileHandler('./logs/application.log', maxBytes=10240, backupCount=5)
fh.setLevel(logging.INFO)  # no matter what level I set here
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
class MyDaemon(Deamon):
    def run(self):
        while True:
            time.sleep(1)
            logger.info('Inside Running Method')

它仅适用于父类的 init 方法 我希望tailf -f application.log文件并查看日志消息。我怎样才能使它发挥作用?

我也想知道是否有可能将logger传递给派生所以在派生中不需要redfine日志记录对象我也在pycharm中调试它没有异常并且它在run方法中循环而不是记录..

1 个答案:

答案 0 :(得分:1)

您应该在范围内创建一个指向日志记录对象的变量。来自logging docs

  

对具有相同名称的getLogger()的多次调用将始终返回对同一Logger对象的引用。

因此,最初设置了记录器对象,然后在您想要记录内容的任何地方,请致电getLogger()。在你的课堂上,最好在__init__中完成,并制作一个实例属性,即:

self.log = logging.getLogger()