logHandler module

Utilities and classes to manage logging in NVDA

logHandler._NVDA_CODE_PATH = 'C:\\nvda\\source'

Store path in which NVDA code is placed. We cannot use globalVars.appDir, since for binary builds it points to the directory with NVDA binaries, whereas for compiled versions NVDA’s code files are in library.zip.

logHandler.getFormattedStacksForAllThreads() str

Generates a string containing a call stack for every Python thread in this process.

The generated string is suitable for logging.

logHandler.isPathExternalToNVDA(path: str) bool

Checks if the given path is external to NVDA (I.e. not pointing to built-in code).

logHandler.getCodePath(f)

Using a frame object, gets its module path (relative to the current directory).[className.[funcName]] @param f: the frame object to use @type f: frame @returns: the dotted module.class.attribute path @rtype: string

logHandler._onErrorSoundRequested: extensionPoints.Action | None = None

Triggered every time an error sound needs to be played. When nvwave is initialized, it registers the handler responsible for playing the error sound. This extension point should not be used directly but retrieved calling getOnErrorSoundRequested() instead. It has been encapsulated in a function to avoid circular import.

logHandler.getOnErrorSoundRequested() extensionPoints.Action

Creates _onErrorSoundRequested extension point if needed (i.e. on first use only) and returns it.

logHandler.shouldPlayErrorSound() bool

Indicates if an error sound should be played when an error is logged.

logHandler.stripBasePathFromTracebackText(text)
class logHandler.Logger(name, level=0)

Bases: Logger

Initialize the logger with a name and an optional level.

DEBUG = 10
INFO = 20
WARNING = 30
WARN = 30
ERROR = 40
CRITICAL = 50
IO = 12
DEBUGWARNING = 15
OFF = 100
fragmentStart = None

The start position of a fragment of the log file as marked with L{markFragmentStart} for later retrieval using L{getFragment}. @type: C{long}

_log(level, msg, args, exc_info=None, extra=None, codepath=None, activateLogViewer=False, stack_info=None)

Low-level logging routine which creates a LogRecord and then calls all the handlers of this logger to handle the record.

debugWarning(msg, *args, **kwargs)

Log ‘msg % args’ with severity ‘DEBUGWARNING’.

io(msg, *args, **kwargs)

Log ‘msg % args’ with severity ‘IO’.

exception(msg: str = '', exc_info: Literal[True] | tuple[type[BaseException] | None, BaseException | None, TracebackType | None] | BaseException = True, **kwargs)

Log an exception at an appropriate level. Normally, it will be logged at level “ERROR”. However, certain exceptions which aren’t considered errors (or aren’t errors that we can fix) are expected and will therefore be logged at a lower level.

markFragmentStart()

Mark the current end of the log file as the start position of a fragment to be later retrieved by L{getFragment}. @returns: Whether a log file is in use and a position could be marked @rtype: bool

getFragment()

Retrieve a fragment of the log starting from the position marked using L{markFragmentStart}. If L{fragmentStart} does not point to the current end of the log file, it is reset to C{None} after reading the fragment. @returns: The text of the fragment, or C{None} if L{fragmentStart} is None. @rtype: str

class logHandler.RemoteHandler

Bases: Handler

Initializes the instance - basically setting the formatter to None and the filter list to empty.

emit(record)

Do whatever it takes to actually log the specified logging record.

This version is intended to be implemented by subclasses and so raises a NotImplementedError.

class logHandler.FileHandler(filename, mode='a', encoding=None, delay=False, errors=None)

Bases: FileHandler

Open the specified file and use it as the stream for logging.

handle(record)

Conditionally emit the specified logging record.

Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of the I/O thread lock. Returns whether the filter passed the record for emission.

class logHandler.Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)

Bases: Formatter

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 or string.Template formatting in your format string.

Changed in version 3.2: Added the style parameter.

default_time_format = '%H:%M:%S'
default_msec_format = '%s.%03d'
formatException(ex)

Format and return the specified exception information as a string.

This default implementation just uses traceback.print_exception()

format(record: LogRecord) str

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.

formatTime(record: LogRecord, datefmt: str | None = None) str

Custom implementation of formatTime which avoids time.localtime since it causes a crash under some versions of Universal CRT when Python locale is set to a Unicode one (#12160, Python issue 36792)

class logHandler.StreamRedirector(name, logger, level)

Bases: object

Redirects an output stream to a logger.

Constructor. @param name: The name of the stream to be used in the log output. @param logger: The logger to which to log. @type logger: L{Logger} @param level: The level at which to log. @type level: int

write(text)
flush()
logHandler.redirectStdout(logger)

Redirect stdout and stderr to a given logger. @param logger: The logger to which to redirect. @type logger: L{Logger}

logHandler.log: Logger = <Logger nvda (WARNING)>

The singleton logger instance.

logHandler.logHandler: Handler | None = None

The singleton log handler instance.

logHandler._getDefaultLogFilePath()
logHandler._excepthook(*exc_info)
class logHandler._ThreadExceptHookArgs_t(exc_type, exc_value, exc_traceback, thread)

Bases: NamedTuple

Create new instance of _ThreadExceptHookArgs_t(exc_type, exc_value, exc_traceback, thread)

exc_type: type[BaseException]

Alias for field number 0

exc_value: BaseException | None

Alias for field number 1

exc_traceback: TracebackType | None

Alias for field number 2

thread: Thread | None

Alias for field number 3

_asdict()

Return a new dict which maps field names to their values.

_field_defaults = {}
_fields = ('exc_type', 'exc_value', 'exc_traceback', 'thread')
classmethod _make(iterable)

Make a new _ThreadExceptHookArgs_t object from a sequence or iterable

_replace(**kwds)

Return a new _ThreadExceptHookArgs_t object replacing specified fields with new values

logHandler._threadExceptHook(excInfoObj: _ThreadExceptHookArgs_t) None
class logHandler._UnraisableHookArgs(*args, **kwargs)

Bases: Protocol

exc_type: type[BaseException]
exc_value: BaseException | None
exc_traceback: TracebackType | None
err_msg: str | None
object: object
_abc_impl = <_abc._abc_data object>
_is_protocol = True
logHandler._unraisableExceptHook(unraisable: _UnraisableHookArgs) None
logHandler._showwarning(message, category, filename, lineno, file=None, line=None)
logHandler._shouldDisableLogging() bool

Disables logging based on command line options and if secure mode is active. See NoConsoleOptionParser in nvda.pyw, #TODO and #8516.

Secure mode disables logging. Logging on secure screens could allow keylogging of passwords and retrieval from the SYSTEM user.

  • --secure overrides any logging preferences by disabling logging.

  • --debug-logging or --log-level=X overrides the user config log level setting.

  • --debug-logging and --log-level=X override --no-logging.

logHandler.initialize(shouldDoRemoteLogging=False)

Initialize logging. This must be called before any logging can occur. @precondition: The command line arguments have been parsed into L{globalVars.appArgs}. @var shouldDoRemoteLogging: True if all logging should go to the real NVDA via rpc (for slave) @type shouldDoRemoteLogging: bool

logHandler.isLogLevelForced() bool

Check if the log level was overridden either from the command line or because of secure mode.

logHandler.setLogLevelFromConfig()

Set the log level based on the current configuration.