App Engine Python SDK version 1.9.2
[gae.git] / python / google / appengine / api / app_logging.py
blobb718d0fe5d7416b627e8ea0a7eb50c8d80ad9152
1 #!/usr/bin/env python
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.
24 Classes defined here:
25 AppLogsHandler: StreamHandler subclass
26 """
36 import logging
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
48 application logs.
50 This handler will output log statements to logservice.write(). This handler is
51 automatically initialized and attached to the Python common logging library.
52 """
67 def emit(self, record):
68 """Emit a record.
70 This implementation is based on the implementation of
71 StreamHandler.emit()."""
72 try:
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):
80 raise
81 except:
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),
95 message)
97 def _AppLogsLevel(self, level):
98 """Converts the logging level used in Python to the API logging level"""
99 if level >= logging.CRITICAL:
100 return 4
101 elif level >= logging.ERROR:
102 return 3
103 elif level >= logging.WARNING:
104 return 2
105 elif level >= logging.INFO:
106 return 1
107 else:
108 return 0