如何使Django/谷歌应用程序引擎中的日志颜色?

时间:2022-02-18 15:17:43

If one iswriting a Django/ Google App Engine application and would like to have logs that are conveniently conspicuous based on color (i.e. errors in red), how does one set that up?

如果有人正在编写Django/谷歌应用程序引擎应用程序,并且希望有基于颜色(即错误为红色)的日志,那么如何设置日志呢?

I've copied the helpful solution from this question, but I'm not sure how to integrate it into Django/Google App Engine.

我已经从这个问题中复制了有用的解决方案,但是我不知道如何将它集成到Django/谷歌应用程序引擎中。

I figured one would put the following in the application's main.py (i.e. essentially from the example here: Running Django on Google App Engine):

我想应该在应用程序的主程序中加入以下内容。py(即从这里的示例来看:在谷歌App引擎上运行Django):

from contrib.utils import ColouredLogger # from the SO question above
logging.setLoggerClass(ColouredLogger)

... where contrib.utils is where I put airmind's code from the above link to his SO answer.

…普通发布版。utils是我把从上面链接到他的SO答案的airmind的代码。

However, that doesn't seem to do anything to the output to the console for GAE, which continues to be in the original format + plain color.

然而,这似乎对GAE的控制台输出没有任何影响,GAE仍然采用原始格式+纯色。

Suggestions and input would be much appreciated.

非常感谢您的建议和投入。

Cheers, Brian

欢呼,布莱恩

6 个解决方案

#1


18  

We use colorlog and it does exactly what you expect.

我们使用的是colorlog,它和您预期的一样。

For posterity, the formatter config we use is:

对于后代,我们使用的格式化程序配置是:

'color': {
    '()': 'colorlog.ColoredFormatter',
    'format': '%(log_color)s%(levelname)-8s %(message)s',
    'log_colors': {
        'DEBUG':    'bold_black',
        'INFO':     'white',
        'WARNING':  'yellow',
        'ERROR':    'red',
        'CRITICAL': 'bold_red',
    },
}

#2


7  

Django already has support for color output through the 'DJANGO_COLORS' environment variable used for example when running the built in development server. Some person has noticed this and created a plug-and-play solution https://github.com/tiliv/django-colors-formatter; with that package on the project's python path my logging settings.py is as follow:

Django已经支持通过'DJANGO_COLORS'环境变量进行颜色输出,例如在运行内置的开发服务器时。有人注意到了这一点,并创建了一个即插即用的解决方案https://github.com/tiliv/django-colors-formatter;在项目的python路径上,我的日志记录设置。py是:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'formatters': {
        'verbose': {
            '()': 'djangocolors_formatter.DjangoColorsFormatter', # colored output
            'format': '%(levelname)s %(name)s %(asctime)s %(module)s %(process)d %(thread)d %(pathname)s@%(lineno)s: %(message)s'
        },
        'simple': {
            '()': 'djangocolors_formatter.DjangoColorsFormatter', # colored output
            'format': '%(levelname)s %(name)s %(filename)s@%(lineno)s: %(message)s'
        },
    },
     # omitting the handler 'level' setting so that all messages are passed and we do level filtering in 'loggers'
    'handlers': {
        'null': {
            'class':'django.utils.log.NullHandler',
        },
        'console':{
            'class':'logging.StreamHandler',
            'formatter': 'simple',
        },
        'mail_admins': {
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler',
            'formatter': 'verbose'
        }
    },
    'loggers': {
        '': { 
            'handlers': ['mail_admins', 'console'],
            'level': 'WARNING',
        },
    }
}

Sample console logging output using django-colors-formatter: 如何使Django/谷歌应用程序引擎中的日志颜色?

使用django-colors-formatter的示例控制台日志输出:

#3


4  

I also wanted color output for the dev_appserver. I found the solutions here a little OTT (all I wanted was to make my logging.error() calls stand out. I ended up monkeypatching the logging module by dropping this in my main.py as a quick solution:

我还需要为dev_appserver输出颜色。我发现这里的解决方案有点过分(我只想让我的logger .error()调用脱颖而出。最后,我在我的主程序中删除了日志模块。py作为一个快速解决方案:

# monkey patch logger to dump ERRORs in red
import os
if os.environ['SERVER_SOFTWARE'].find('Development') >= 0:
    import logging
    old_error = logging.error
    def red_error(msg,*args,**kwargs):
        old_error("\033[22;31m%s\033[0;0m" % msg, *args, **kwargs)
    logging.error = red_error

This will only for on ANSI-color terminals.

这只适用于ANSI-color终端。

#4


2  

The reset codes mentioned in the answer you linked to will work on a console in the local development server (but will likely take some tweaking - you'll have to chain it with the existing App Engine logging handler), but won't work in production, since in production log entries are output to an HTML page in your admin console.

回答你提到的重置密码链接将会在一个在当地开发服务器控制台(但可能会采取一些调整——你必须链与现有应用程序引擎日志处理程序),但不会在生产工作,因为在生产日志条目在管理控制台输出一个HTML页面。

You can, however, filter by log level in the admin console.

但是,您可以在管理控制台中按日志级别进行过滤。

#5


2  

I don't believe that you should create a logger subclass just for this - airmind's answer is fine as far as creating a specialised Formatter and specifying its use on a StreamHandler. But there's no need for a logger subclass. In fact airmind's use of a logger class adds a handler to every logger created, which is not what you want.

我不认为您应该创建一个logger子类仅仅为了这个——airmind的答案是好的,只要创建一个专门化的格式化程序并指定它在一个StreamHandler上的使用。但是不需要一个日志程序子类。事实上,airmind对logger类的使用为每个创建的logger添加了一个处理程序,这不是您想要的。

The solution airmind gave only works for terminals which support ANSI escape sequences - are you sure that your console does support them?

airmind给出的解决方案只适用于支持ANSI转义序列的终端——您确定您的控制台支持它们吗?

#6


2  

Here is a sample formater:

这是一个模板示例:

class Formatter(logging.Formatter) :
    _level_colors  = {
      "DEBUG": "\033[22;32m", "INFO": "\033[01;34m",
      "WARNING": "\033[22;35m", "ERROR": "\033[22;31m",
      "CRITICAL": "\033[01;31m"
     };    

    def format(self, record):
        if(Formatter._level_colors.has_key(record.levelname)):
            record.levelname = "%s%s\033[0;0m" % \
                            (Formatter._level_colors[record.levelname],
                             record.levelname)
        record.name = "\033[37m\033[1m%s\033[0;0m" % record.name
        return logging.Formatter.format(self, record)    

You need to configure it, for example:

您需要对其进行配置,例如:

...
[formatters]
keys=console_formatter
...
[handler_console_handler]
class=StreamHandler
formatter=console_formatter
args=(sys.stdout,)

#1


18  

We use colorlog and it does exactly what you expect.

我们使用的是colorlog,它和您预期的一样。

For posterity, the formatter config we use is:

对于后代,我们使用的格式化程序配置是:

'color': {
    '()': 'colorlog.ColoredFormatter',
    'format': '%(log_color)s%(levelname)-8s %(message)s',
    'log_colors': {
        'DEBUG':    'bold_black',
        'INFO':     'white',
        'WARNING':  'yellow',
        'ERROR':    'red',
        'CRITICAL': 'bold_red',
    },
}

#2


7  

Django already has support for color output through the 'DJANGO_COLORS' environment variable used for example when running the built in development server. Some person has noticed this and created a plug-and-play solution https://github.com/tiliv/django-colors-formatter; with that package on the project's python path my logging settings.py is as follow:

Django已经支持通过'DJANGO_COLORS'环境变量进行颜色输出,例如在运行内置的开发服务器时。有人注意到了这一点,并创建了一个即插即用的解决方案https://github.com/tiliv/django-colors-formatter;在项目的python路径上,我的日志记录设置。py是:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'formatters': {
        'verbose': {
            '()': 'djangocolors_formatter.DjangoColorsFormatter', # colored output
            'format': '%(levelname)s %(name)s %(asctime)s %(module)s %(process)d %(thread)d %(pathname)s@%(lineno)s: %(message)s'
        },
        'simple': {
            '()': 'djangocolors_formatter.DjangoColorsFormatter', # colored output
            'format': '%(levelname)s %(name)s %(filename)s@%(lineno)s: %(message)s'
        },
    },
     # omitting the handler 'level' setting so that all messages are passed and we do level filtering in 'loggers'
    'handlers': {
        'null': {
            'class':'django.utils.log.NullHandler',
        },
        'console':{
            'class':'logging.StreamHandler',
            'formatter': 'simple',
        },
        'mail_admins': {
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler',
            'formatter': 'verbose'
        }
    },
    'loggers': {
        '': { 
            'handlers': ['mail_admins', 'console'],
            'level': 'WARNING',
        },
    }
}

Sample console logging output using django-colors-formatter: 如何使Django/谷歌应用程序引擎中的日志颜色?

使用django-colors-formatter的示例控制台日志输出:

#3


4  

I also wanted color output for the dev_appserver. I found the solutions here a little OTT (all I wanted was to make my logging.error() calls stand out. I ended up monkeypatching the logging module by dropping this in my main.py as a quick solution:

我还需要为dev_appserver输出颜色。我发现这里的解决方案有点过分(我只想让我的logger .error()调用脱颖而出。最后,我在我的主程序中删除了日志模块。py作为一个快速解决方案:

# monkey patch logger to dump ERRORs in red
import os
if os.environ['SERVER_SOFTWARE'].find('Development') >= 0:
    import logging
    old_error = logging.error
    def red_error(msg,*args,**kwargs):
        old_error("\033[22;31m%s\033[0;0m" % msg, *args, **kwargs)
    logging.error = red_error

This will only for on ANSI-color terminals.

这只适用于ANSI-color终端。

#4


2  

The reset codes mentioned in the answer you linked to will work on a console in the local development server (but will likely take some tweaking - you'll have to chain it with the existing App Engine logging handler), but won't work in production, since in production log entries are output to an HTML page in your admin console.

回答你提到的重置密码链接将会在一个在当地开发服务器控制台(但可能会采取一些调整——你必须链与现有应用程序引擎日志处理程序),但不会在生产工作,因为在生产日志条目在管理控制台输出一个HTML页面。

You can, however, filter by log level in the admin console.

但是,您可以在管理控制台中按日志级别进行过滤。

#5


2  

I don't believe that you should create a logger subclass just for this - airmind's answer is fine as far as creating a specialised Formatter and specifying its use on a StreamHandler. But there's no need for a logger subclass. In fact airmind's use of a logger class adds a handler to every logger created, which is not what you want.

我不认为您应该创建一个logger子类仅仅为了这个——airmind的答案是好的,只要创建一个专门化的格式化程序并指定它在一个StreamHandler上的使用。但是不需要一个日志程序子类。事实上,airmind对logger类的使用为每个创建的logger添加了一个处理程序,这不是您想要的。

The solution airmind gave only works for terminals which support ANSI escape sequences - are you sure that your console does support them?

airmind给出的解决方案只适用于支持ANSI转义序列的终端——您确定您的控制台支持它们吗?

#6


2  

Here is a sample formater:

这是一个模板示例:

class Formatter(logging.Formatter) :
    _level_colors  = {
      "DEBUG": "\033[22;32m", "INFO": "\033[01;34m",
      "WARNING": "\033[22;35m", "ERROR": "\033[22;31m",
      "CRITICAL": "\033[01;31m"
     };    

    def format(self, record):
        if(Formatter._level_colors.has_key(record.levelname)):
            record.levelname = "%s%s\033[0;0m" % \
                            (Formatter._level_colors[record.levelname],
                             record.levelname)
        record.name = "\033[37m\033[1m%s\033[0;0m" % record.name
        return logging.Formatter.format(self, record)    

You need to configure it, for example:

您需要对其进行配置,例如:

...
[formatters]
keys=console_formatter
...
[handler_console_handler]
class=StreamHandler
formatter=console_formatter
args=(sys.stdout,)