python - CherryPy 日志记录 : How do I configure and use the global and application level loggers?

标签 python logging cherrypy

我在登录时遇到了问题。我正在运行 CherryPy 3.2 并且我一直在阅读文档 here , 但还没有找到任何关于如何为输出配置本地日志文件以及如何写入它的示例。

覆盆子.py:


import socket
import sys
import cherrypy

app_roots = {
                # Sean's laptop dev environment.
                "mylaptop": "/home/src/local-mydomain.com/py",

                # Hosted dev environment.  
                "mydomain.com" : "/home/dev/src/py"
            }


hostname = socket.gethostname()
CherryPyLog = cherrypy.tree.mount().log

if hostname not in app_roots:
    CherryPyLog("The following hostname does not have an app_root entry in raspberry.py.  Exiting early.")
    sys.exit()

sys.stdout = sys.stderr
sys.path.append(app_roots[hostname])

import os
os.chdir(app_root)

# Setup for raspberry application logging.
import datetime
today = datetime.datetime.today()
log.access_file = "{0}/{1}.raspberry.access.log".format(app_roots[hostname],today.strftime("%Y%m%d-%H%M"))
log.error_file = "{0}/{1}.raspberry.error.log".format(app_roots[hostname],today.strftime("%Y%m%d-%H%M"))

#Testing logger
log("{0} -- Logger configured".format(today.strftime("%Y%m%d-%H%M%S")))

import atexit
cherrypy.config.update({'environment': 'embedded'})

if cherrypy.__version__.startswith('3.0') and cherrypy.engine.state == 0:
    cherrypy.engine.start(blocking = False)
    atexit.register(cherrypy.engine.stop)

from web.controllers.root import RaspberryRequestHandler

application = cherrypy.Application(RaspberryRequestHandler(), script_name = None, config = None)

更新:这是我最终使用的代码块。



app_roots = {
                # Sean's laptop dev environment.
                "mylaptop": "/home/src/local-plottools.com/py",

                # Hosted dev environment.  
                "myDomain" : "/home/dev/src/py"
            }

import socket
hostname = socket.gethostname()

import cherrypy
import sys
if hostname not in app_roots:
    cherrypy.log("The hostname {0} does not have an app_root entry in {1}.  Exiting early.".format(hostname,__file__))
    sys.exit()

sys.stdout = sys.stderr
sys.path.append(app_roots[hostname])

import os
os.chdir(app_roots[hostname])

from web.controllers.root import RaspberryRequestHandler

cherrypy.config.update({
    'log.access_file': "{0}/cherrypy-access.log".format(app_roots[hostname]),
    'log.error_file': "{0}/cherrypy.log".format(app_roots[hostname]),
    "server.thread_pool" : 10
})

# special case, handling debug sessions when quickstart is needed.
if __name__ == "__main__":

    cherrypy.config.update({
                                'log.screen': True, 
                                "server.socket_port": 8000
                            })
    cherrypy.quickstart(RaspberryRequestHandler())
    sys.exit()

# This configuration is needed for running under mod_wsgi.  See here:  http://tools.cherrypy.org/wiki/ModWSGI    
cherrypy.config.update({'environment': 'embedded'})

applicationLogName = "{0}/raspberry.log".format(app_roots[hostname])

from logging import handlers
applicationLogFileHandler = handlers.RotatingFileHandler(applicationLogName, 'a', 10000000, 1000)

import logging
applicationLogFileHandler.setLevel(logging.DEBUG)

from cherrypy import _cplogging
applicationLogFileHandler.setFormatter(_cplogging.logfmt)

cherrypy.log.error_log.addHandler(applicationLogFileHandler)

application = cherrypy.Application(RaspberryRequestHandler(), None)

最佳答案

稍微简化一下:

import os
import socket
import sys

import cherrypy

app_roots = {
                # Sean's laptop dev environment.
                "mylaptop": "/home/src/local-mydomain.com/py",

                # Hosted dev environment.  
                "mydomain.com" : "/home/dev/src/py"
            }


hostname = socket.gethostname()
if hostname not in app_roots:
    cherrypy.log("The hostname %r does not have an app_root entry in "
                 "raspberry.py.  Exiting early." % hostname)
    sys.exit()

sys.path.append(app_roots[hostname])
os.chdir(app_root)

cherrypy.config.update({
    'environment': 'embedded',
    'log.access_file': "{0}/raspberry.access.log".format(app_roots[hostname]),
    'log.error_file': "{0}/raspberry.error.log".format(app_roots[hostname]),
    })

from web.controllers.root import RaspberryRequestHandler
application = cherrypy.tree.mount(RaspberryRequestHandler(), '/')
# Insert log changes here
cherrypy.engine.start()

如果您每天需要不同的日志,请使用 http://www.cherrypy.org/wiki/Logging#CustomHandlers 中描述的 RotatingFileHandler我认为您遗漏的重要一点是,您应该只在实例化您的应用程序(例如通过 tree.mount(),如上所述)之后才处理 app.log,但是 之前 engine.start。即对于错误日志:

application = cherrypy.tree.mount(RaspberryRequestHandler(), '/')

log = application.log
log.error_file = ""

# Make a new RotatingFileHandler for the error log.
fname = "{0}/raspberry.error.log".format(app_roots[hostname])
h = handlers.RotatingFileHandler(fname, 'a', 10000000, 1000)
h.setLevel(DEBUG)
h.setFormatter(_cplogging.logfmt)
log.error_log.addHandler(h)

cherrypy.engine.start()

希望对您有所帮助...

关于python - CherryPy 日志记录 : How do I configure and use the global and application level loggers?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4056958/

相关文章:

python - 在调用打印函数时增加一个变量

java - SLF4J 最佳实践

asp.net-mvc-3 - 使用 Essential.Diagnostics 存储日志文件的相对路径

python - Cherrypy:无法获取我的 POST 数据

python - 如何顺序组合2个 tensorflow 模型?

python - Pandas :如何在使用 read_csv 时获取行读取状态?

python BeautifulSoup查找span id名称而不使用string\re方法

spring - 如何在Spring Boot中设置嵌入式tomcat的日志级别?

python - CherryPy:如何在更新数据时停止和缓冲传入请求

java - Android 和 CherryPy