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.
22 """Logging utilities for use by applications.
25 AppLogsHandler: StreamHandler subclass
38 from google
.appengine
import runtime
39 from google
.appengine
.api
import logservice
44 NEWLINE_REPLACEMENT
= "\0"
46 class AppLogsHandler(logging
.Handler
):
47 """Logging handler that will direct output to a persistent store of
50 This handler will output log statements to logservice.write(). This handler is
51 automatically initialized and attached to the Python common logging library.
67 def emit(self
, record
):
70 This implementation is based on the implementation of
71 StreamHandler.emit()."""
73 message
= self
._AppLogsMessage
(record
)
74 if isinstance(message
, unicode):
75 message
= message
.encode("UTF-8")
78 logservice
.write(message
)
79 except (KeyboardInterrupt, SystemExit, runtime
.DeadlineExceededError
):
82 self
.handleError(record
)
84 def _AppLogsMessage(self
, record
):
85 """Converts the log record into a log line."""
89 message
= self
.format(record
).replace("\r\n", NEWLINE_REPLACEMENT
)
90 message
= message
.replace("\r", NEWLINE_REPLACEMENT
)
91 message
= message
.replace("\n", NEWLINE_REPLACEMENT
)
93 return "LOG %d %d %s\n" % (self
._AppLogsLevel
(record
.levelno
),
94 long(record
.created
* 1000 * 1000),
97 def _AppLogsLevel(self
, level
):
98 """Converts the logging level used in Python to the API logging level"""
99 if level
>= logging
.CRITICAL
:
101 elif level
>= logging
.ERROR
:
103 elif level
>= logging
.WARNING
:
105 elif level
>= logging
.INFO
: