1.9.30 sync.
[gae.git] / python / google / appengine / api / app_logging.py
blobd591da8a9e53877348c9b8df18f930018e5a32bf
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 """
37 import logging
39 from google.appengine import runtime
40 from google.appengine.api import logservice
45 NEWLINE_REPLACEMENT = "\0"
47 class AppLogsHandler(logging.Handler):
48 """Logging handler that will direct output to a persistent store of
49 application logs.
51 This handler will output log statements to logservice.write(). This handler is
52 automatically initialized and attached to the Python common logging library.
53 """
68 def emit(self, record):
69 """Emit a record.
71 This implementation is based on the implementation of
72 StreamHandler.emit()."""
73 try:
74 message = self._AppLogsMessage(record)
75 if isinstance(message, unicode):
76 message = message.encode("UTF-8")
79 logservice.write(message)
80 except (KeyboardInterrupt, SystemExit, runtime.DeadlineExceededError):
81 raise
82 except:
83 self.handleError(record)
85 def _AppLogsMessage(self, record):
86 """Converts the log record into a log line."""
90 message = self.format(record).replace("\r\n", NEWLINE_REPLACEMENT)
91 message = message.replace("\r", NEWLINE_REPLACEMENT)
92 message = message.replace("\n", NEWLINE_REPLACEMENT)
94 return "LOG %d %d %s\n" % (self._AppLogsLevel(record.levelno),
95 long(record.created * 1000 * 1000),
96 message)
98 def _AppLogsLevel(self, level):
99 """Converts the logging level used in Python to the API logging level"""
100 if level >= logging.CRITICAL:
101 return 4
102 elif level >= logging.ERROR:
103 return 3
104 elif level >= logging.WARNING:
105 return 2
106 elif level >= logging.INFO:
107 return 1
108 else:
109 return 0