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.
19 """Utility methods for working with logs."""
27 REQUEST_LOG_ID
= 'REQUEST_LOG_ID'
36 LOG_LEVEL_CRITICAL
= 4
38 LOG_LEVELS
= [LOG_LEVEL_DEBUG
,
46 _DEFAULT_LEVEL
= LOG_LEVEL_ERROR
49 def _CurrentTimeMicro():
50 return int(time
.time() * _U_SEC
)
54 return e
.replace('\0', '\n')
58 """Returns the ID of the current request assigned by App Engine."""
59 return os
.environ
.get(REQUEST_LOG_ID
, None)
62 def _StrictParseLogEntry(entry
):
63 """Parses a single log entry emitted by app_logging.AppLogsHandler.
65 Parses a log entry of the form LOG <level> <timestamp> <message> where the
66 level is in the range [0, 4]. If the entry is not of that form, ValueError is
70 entry: The log entry to parse.
73 A (timestamp, level, message) tuple.
76 ValueError: if the entry failed to be parsed.
78 magic
, level
, timestamp
, message
= entry
.split(' ', 3)
82 timestamp
, level
= int(timestamp
), int(level
)
83 if level
not in LOG_LEVELS
:
86 return timestamp
, level
, _Clean(message
)
89 def ParseLogEntry(entry
):
90 """Parses a single log entry emitted by app_logging.AppLogsHandler.
92 Parses a log entry of the form LOG <level> <timestamp> <message> where the
93 level is in the range [0, 4]. If the entry is not of that form, take the whole
94 entry to be the message. Null characters in the entry are replaced by
98 entry: The log entry to parse.
101 A (timestamp, level, message) tuple.
104 return _StrictParseLogEntry(entry
)
107 return _CurrentTimeMicro(), _DEFAULT_LEVEL
, _Clean(entry
)
111 """Parses a str containing newline separated log entries.
113 Parses a series of log entries in the form LOG <level> <timestamp> <message>
114 where the level is in the range [0, 4]. Null characters in the entry are
115 replaced by newlines.
118 logs: A string containing the log entries.
121 A list of (timestamp, level, message) tuples.
123 return [ParseLogEntry(line
) for line
in logs
.split('\n') if line
]