djblets.log¶
Logging support.
This can be used to offer some advanced logging capabilities.
Note that this predates Django’s modern logging support, and is here primarily for compatibility.
Settings¶
The following settings control logging.
LOGGING_ENABLED¶
Default: False
Sets whether or not logging is enabled.
LOGGING_DIRECTORY¶
Default: None
Specifies the directory that log files should be stored in. This directory must be writable by the process running Django.
LOGGING_NAME¶
Default: None
The name of the log files, excluding the extension and path. This will usually be the name of the website or web application. The file extension will be automatically appended when the file is written.
LOGGING_ALLOW_PROFILING¶
Default: False
Specifies whether or not code profiling is allowed. If True, visiting
any page with a ?profiling=1 parameter in the URL will cause the
request to be profiled and stored in a .prof file using the defined
LOGGING_DIRECTORY and LOGGING_NAME.
LOGGING_LINE_FORMAT¶
Default: "%(asctime)s - %(levelname)s - %(message)s"
The format for lines in the log file. See Python’s logging
documentation for possible values in the format string.
LOGGING_PAGE_TIMES¶
Default: False
If enabled, page access times will be logged. Specifically, it will log the initial request, the finished render and response, and the total time it look.
The username and page URL will be included in the logs.
LOGGING_LEVEL¶
Default: "DEBUG"
The minimum level to log. Possible values are "DEBUG", "INFO",
"WARNING", "ERROR" and "CRITICAL".
LOGGING_BLACKLIST¶
Default: ['django.db.backends']
A list of logger names to exclude from the logs. Each logger with the given name will be filtered out, along with any descendents of those loggers.
LOGGING_TO_STDOUT¶
New in version 1.0.17.
New in version 2.2.
Default: False
Whether to log output to stdout. This would be in addition to any other configured logging, and is intended for environments like Docker.
- class TimedLogInfo(*, message: str, warning_at: float, critical_at: float, default_level: int, log_beginning: bool, request: Optional[HttpRequest], extra: Mapping[str, object] = {}, logger: Optional[logging.Logger] = None, trace_id: Optional[str] = None)[source]¶
Bases:
objectTracks the time between operations for logging purposes.
This is created and returned by
log_timed()to track how long an operation takes, warning or critical-erroring if it takes too long.- __init__(*, message: str, warning_at: float, critical_at: float, default_level: int, log_beginning: bool, request: Optional[HttpRequest], extra: Mapping[str, object] = {}, logger: Optional[logging.Logger] = None, trace_id: Optional[str] = None) None[source]¶
Initialize the state for the timer.
Changed in version 6.0:
This now expects keyword-only arguments. This will be required in Djblets 7.
Added
extra,logger, andtrace_idarguments.warning_atand critical_at` now support fractions of seconds.
- Parameters:
message (
str) – The message to show for the log entries.,warning_at (
float) –The number of seconds at which to log warnings.
This may contain fractions of seconds.
Changed in version 6.0: This now supports fractions of seconds.
critical_at (
float) –The number of seconds at which to log critical errors.
This may contain fractions of seconds.
Changed in version 6.0: This now supports fractions of seconds.
default_level (
int) – The default log level for the timing information.log_beginning (
bool) – Whether to log the beginning time for the operation.request (
django.http.HttpRequest, optional) – The HTTPoptional HTTP request associated with the operation.extra (
dict, optional) –Extra information to include with all log items.
This will be populated with
requestandtrace_id.New in version 6.0.
logger (
logging.Logger, optional) –The logger used for all log entries.
New in version 6.0.
trace_id (
str, optional) –The trace ID to include in log messages.
This is used to help follow the chain of events in a series of logs.
New in version 6.0.
- start_time: datetime¶
The start date/time for the operation.
- request: Optional[HttpRequest]¶
The optional HTTP request associated with the operation.
- extra: Mapping[str, object]¶
Extra information to include with all log items.
This will be populated with
request.New in version 6.0.
- logger: logging.Logger¶
The logger used for all log entries.
New in version 6.0.
- trace_id: str¶
The trace ID to include in log messages.
This is used to help follow the chain of events in a series of logs.
New in version 6.0.
- __enter__() TimedLogInfo[source]¶
Enter the context for the timer.
This will open the context and return itself, allowing the timer to automatically complete when the context ends.
- Context:
TimedLogInfo– This object.
- __exit__(*args, **kwargs) Literal[False][source]¶
Exit the context for the timer.
This will log the end time of the operation, stopping the timer.
- done() None[source]¶
Stop the timed logging operation.
The resulting time of the operation will be written to the log file. The log level depends on how long the operation takes.
- __annotations__ = {'critical_at': 'float', 'default_level': 'int', 'extra': 'Mapping[str, object]', 'logger': 'logging.Logger', 'message': 'str', 'request': 'Optional[HttpRequest]', 'start_time': 'datetime', 'trace_id': 'str', 'warning_at': 'float'}¶
- class RequestLogFormatter(request_fmt, *args, **kwargs)[source]¶
Bases:
Formatter- __init__(request_fmt, *args, **kwargs)[source]¶
Initialize the formatter with specified format strings.
Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.
Use a style parameter of ‘%’, ‘{’ or ‘$’ to specify that you want to use one of %-formatting,
str.format()({}) formatting orstring.Templateformatting in your format string.Changed in version 3.2: Added the
styleparameter.
- format(record)[source]¶
Format the specified record as text.
The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.
- format_request(request)[source]¶
Return formatted request information for the log message.
The returned string will be based off the configured
settings.LOGGING_REQUEST_FORMATand keys in the request, if found.If anything from the request is missing, an empty string will be returned.
- Parameters:
request (
django.http.HttpRequest) – The HTTP request from the client.- Returns:
The request-specific string to include in the log message. This may be empty.
- Return type:
- class BlacklistFilter(names)[source]¶
Bases:
FilterBlacklists the provided loggers (and their children) from logging.
- filter(record)[source]¶
Return whether this record should be logged.
The record is only logged if it’s not in the list of any of the loggers on the blacklist, and if it doesn’t have a parent logger listed.
- Parameters:
record (
logging.LogRecord) – The record to filter.- Returns:
Trueif the record can be logged.Falseif it must be ignored.- Return type:
- restart_logging()[source]¶
Restarts the logging. The next page view will set up the loggers based on any new settings.
- log_timed(message: str, *, warning_at: float = 5, critical_at: float = 15, log_beginning: bool = True, default_level: int = 10, request: Optional[HttpRequest] = None, extra: Mapping[str, object] = {}, logger: Optional[logging.Logger] = None, trace_id: Optional[str] = None) TimedLogInfo[source]¶
Times an operation, logging timing information at different thresholds.
This will display a log message at the start of an operation and at the end, displaying the time taken for the operation. The final log entry’s level will depend on the amount of time taken, switching to a warning if at
warning_atseconds and a critical error atcritical_atseconds.This function can be called directly or used as a context manager.
Changed in version 6.0:
This can now be used as a context manager.
Added
extra,logger, andtrace_idarguments.This now expects keyword-only arguments for all but
message. This will be required in Djblets 7.warning_atand critical_at` now support fractions of seconds.
- Parameters:
message (
str) – The message to show for the log entries.,warning_at (
int) –The number of seconds at which to log warnings.
This may contain fractions of seconds.
Changed in version 6.0: This now supports fractions of seconds.
critical_at (
int) –The number of seconds at which to log critical errors.
This may contain fractions of seconds.
Changed in version 6.0: This now supports fractions of seconds.
default_level (
int) – The default log level for the timing information.log_beginning (
bool) – Whether to log the beginning time for the operation.request (
django.http.HttpRequest, optional) – The optional HTTP request associated with the operation.extra (
dict, optional) –Extra information to include with all log items.
This will be populated with
requestandtrace_id.New in version 6.0.
logger (
logging.Logger, optional) –The logger used for all log entries.
New in version 6.0.
trace_id (
str, optional) –The trace ID to include in log messages.
This is used to help follow the chain of events in a series of logs.
If not provided, one will be generated. This can then be accessed on
TimedLogInfo.trace_id.New in version 6.0.
Example
from djblets.log import log_timed # As a direct function call: t = log_timed('Doing a thing') try: ... finally: t.done() # As a context manager: with log_timed('Doing a thing') as t: ...