Add google appengine to repo
[frozenviper.git] / google_appengine / google / appengine / api / app_logging.py
blobe576d3745e3fb55ed534912fb1a273618e68f83c
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.
18 """Logging utilities for use by applications.
20 Classes defined here:
21 AppLogsHandler: StreamHandler subclass
22 """
28 import logging
29 import sys
30 import types
33 NEWLINE_REPLACEMENT = "\0"
36 class AppLogsHandler(logging.StreamHandler):
37 """Logging handler that will direct output to a persistent store of
38 application logs.
40 This handler will output log statements to stderr. This handler is
41 automatically initialized and attached to the Python common logging library.
42 """
47 def __init__(self, stream=None):
48 """Constructor.
50 Args:
51 # stream is optional. it defaults to sys.stderr.
52 stream: destination for output
53 """
54 logging.StreamHandler.__init__(self, stream)
56 def close(self):
57 """Closes the stream.
59 This implementation based on the implementation of FileHandler.close()."""
60 self.flush()
61 self.stream.close()
62 logging.StreamHandler.close(self)
64 def emit(self, record):
65 """Emit a record.
67 This implementation is based on the implementation of
68 StreamHandler.emit()."""
69 try:
70 message = self._AppLogsMessage(record)
71 if isinstance(message, unicode):
72 message = message.encode("UTF-8")
73 self.stream.write(message)
74 self.flush()
75 except (KeyboardInterrupt, SystemExit):
76 raise
77 except:
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),
86 message)
88 def _AppLogsLevel(self, level):
89 """Converts the logging level used in Python to the API logging level"""
90 if level >= logging.CRITICAL:
91 return 4
92 elif level >= logging.ERROR:
93 return 3
94 elif level >= logging.WARNING:
95 return 2
96 elif level >= logging.INFO:
97 return 1
98 else:
99 return 0