3 # Copyright 2007 Google Inc.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
18 """Logging utilities for use by applications.
21 AppLogsHandler: StreamHandler subclass
33 NEWLINE_REPLACEMENT
= "\0"
36 class AppLogsHandler(logging
.StreamHandler
):
37 """Logging handler that will direct output to a persistent store of
40 This handler will output log statements to stderr. This handler is
41 automatically initialized and attached to the Python common logging library.
47 def __init__(self
, stream
=None):
51 # stream is optional. it defaults to sys.stderr.
52 stream: destination for output
54 logging
.StreamHandler
.__init
__(self
, stream
)
59 This implementation based on the implementation of FileHandler.close()."""
62 logging
.StreamHandler
.close(self
)
64 def emit(self
, record
):
67 This implementation is based on the implementation of
68 StreamHandler.emit()."""
70 message
= self
._AppLogsMessage
(record
)
71 if isinstance(message
, unicode):
72 message
= message
.encode("UTF-8")
73 self
.stream
.write(message
)
75 except (KeyboardInterrupt, SystemExit):
78 self
.handleError(record
)
80 def _AppLogsMessage(self
, record
):
81 """Converts the log record into a log line."""
83 message
= self
.format(record
).replace("\n", NEWLINE_REPLACEMENT
)
84 return "LOG %d %d %s\n" % (self
._AppLogsLevel
(record
.levelno
),
85 long(record
.created
* 1000 * 1000),
88 def _AppLogsLevel(self
, level
):
89 """Converts the logging level used in Python to the API logging level"""
90 if level
>= logging
.CRITICAL
:
92 elif level
>= logging
.ERROR
:
94 elif level
>= logging
.WARNING
:
96 elif level
>= logging
.INFO
: