@@ -2279,3 +2279,69 @@ You can of course use the conventional means of decoration::
22792279 @log_if_errors(logger)
22802280 def foo(fail=False):
22812281 ...
2282+
2283+
2284+ .. _utc-formatting :
2285+
2286+ Formatting times using UTC (GMT) via configuration
2287+ --------------------------------------------------
2288+
2289+ Sometimes you want to format times using UTC, which can be done using a class
2290+ such as `UTCFormatter `, shown below::
2291+
2292+ import logging
2293+ import time
2294+
2295+ class UTCFormatter(logging.Formatter):
2296+ converter = time.gmtime
2297+
2298+ and you can then use the `UTCFormatter ` in your code instead of
2299+ :class: `~logging.Formatter `. If you want to do that via configuration, you can
2300+ use the :func: `~logging.config.dictConfig ` API with an approach illustrated by
2301+ the following complete example::
2302+
2303+ import logging
2304+ import logging.config
2305+ import time
2306+
2307+ class UTCFormatter(logging.Formatter):
2308+ converter = time.gmtime
2309+
2310+ LOGGING = {
2311+ 'version': 1,
2312+ 'disable_existing_loggers': False,
2313+ 'formatters': {
2314+ 'utc': {
2315+ '()': UTCFormatter,
2316+ 'format': '%(asctime)s %(message)s',
2317+ },
2318+ 'local': {
2319+ 'format': '%(asctime)s %(message)s',
2320+ }
2321+ },
2322+ 'handlers': {
2323+ 'console1': {
2324+ 'class': 'logging.StreamHandler',
2325+ 'formatter': 'utc',
2326+ },
2327+ 'console2': {
2328+ 'class': 'logging.StreamHandler',
2329+ 'formatter': 'local',
2330+ },
2331+ },
2332+ 'root': {
2333+ 'handlers': ['console1', 'console2'],
2334+ }
2335+ }
2336+
2337+ if __name__ == '__main__':
2338+ logging.config.dictConfig(LOGGING)
2339+ logging.warning('The local time is %s', time.asctime())
2340+
2341+ When this script is run, it should print something like::
2342+
2343+ 2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015
2344+ 2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015
2345+
2346+ showing how the time is formatted both as local time and UTC, one for each
2347+ handler.
0 commit comments