File Logger¶
Summary¶
Set up easily instantiated logging.Logger instances.
Create a few formatters and logging instances that can be easily imported and utilized across the package.
Currently stream_logger() is the easiest and most oft used entry point
in this module.
Exceptions¶
NoUnNamedLoggersException raised when a function in this module is called without a name argument for the logger.
Stream Logging¶
File Logging¶
-
file_logger(filename, logger=None, shell=None, log_level=None, msg_format=None Logging function that emits a
logging.LogRecordtofilename. Logger uses the following formatting by default.:%(asctime)s : %(levelname)s : %(message)s
- Parameters
filename – str File to log a
logging.LogRecordto.logger –
logging.Logger, optional Alogging.Loggerinstantiated in the calling module.
- shell
InteractiveShell, optional Global instance of IPython. Can be None if not run in
IPythonthough this hasn’t been tested.- log_levelint, optional
Level of log records.
- msg_formatstr, optional
Representation of logging messages using parameters accepted by
logging.Formatter. Uses standard % style string formatting.
- Parameters
logger –
logging.Loggerinstance- Raises
AssertionError – shell is not
isinstanceInteractiveShell.
JSON logger¶
Set up a logger that returns properly formatted JSON.
Parameters¶
- loggerstr or
logging.Logger, optional Either a named Logger instance or the string representing the desired instance
- json_formatter
logging.Formatter, optionalJSONFormatterinstance. Included in the listed parameters to be explicit; however, it’s probably easier to not include the parameter as one is configured in the function anyway.
Returns¶
- root_logger
logging.Logger Instance of a
logging.Logger().
Remainder¶
This uses the IPython core IPython.core.logger.LoggingConfigurable
to create a logging.handler.FileHandler that creates one new log
file for every calendar day of the year.
Running IPython instances will continue to write to the log file if the session continues after the point when the logfile rolls over.
If multiple sessions are started, the new instances will append onto the same file as the older ones.
get_history¶
Extract a session from the IPython input history.
Usage¶
Examples¶
python3 ipython-get-history.py 57 record.ipy
Summary for Logger¶
This script is a simple demonstration of
IPython.core.history.HistoryAccessor. It should be possible to build
much more flexible and powerful tools to browse and pull from the history
database. This is a rewrite of that history accessor since IPython’s handling of
history sessions out of the box is oddly limited.
Let’s ignore the direct calls to sys.argv and combine argparse and the magic_argparse functions to make something more durable and useful.
File Logger API¶
output to a file.
Todo
Logging TODOs
- Truncate output if it exceeds a certain threshold.
Run dir(np) or dir(pd) a couple of times and the logs become swamped.
Possibly change that section under the shebang to also include 3 double quotes and in the comment add system info like py version, venv, conda, any of the 1000000 things you could add.
Note
Windows Users
Simulataneous IPython processes may throw.
PermissionError: [WinError 32]
The process cannot access the file because it is being used by another process:
'C:\\Users\\fac\\.ipython\\profile_default\\log\\log-2020-02-26.py' ->
'C:\\Users\\fac\\.ipython\\profile_default\\log\\log-2020-02-26.py.001~'
-
exception
NoUnNamedLoggers(*args, **kwargs)[source][source]¶ Bases:
NotImplementedErrorRaise this error if the logger a function was called with was anonymous.
-
print_history(hist_file=None)[source][source]¶ Write the contents of the running shell’s
sqlitehistory.- Parameters
hist_file (str (
os.Pathlike), optional) – Path to history file. Assume default profile’s history.
-
betterConfig(name=None, parent=None)[source][source]¶ Similar to
logging.basicConfig().- Parameters
- Returns
Anonymous Logger instance.
- Return type
logging.Logger()
Notes
If a
logging.Filterclass is initialized with no args, it’s default behavior is to allow alllogging.LogRecordsto pass.
-
class
ConfigurableLogger(**kwargs)[source][source]¶ Bases:
traitlets.config.configurable.LoggingConfigurable,logging.Logger-
logger: logging.Logger[source]¶
-
-
logging_decorator(f)[source][source]¶ Create a decorator to be used around functions that need to be debugged.
- Parameters
f (function) – The function to decorate
Notes
Calls a logger
-
ipython_logger()[source][source]¶ Saves all commands run in the interactive namespace as valid IPython code.
Warning
This is not necessarily valid python code.
The commands are appended to a file in the directory of the profile in
IPYTHONDIRor fallback to~/.ipython. This file is named based on the date.- Parameters
shell (
InteractiveShell) – Global IPython instance.- Raises
RuntimeError – If the configured logger is already logging to today’s date.
-
class
MyHistoryAccessor(**kwargs)[source][source]¶ Bases:
IPython.core.history.HistoryAccessorModified HistoryAccessor to fetch the whole ipython history across all sessions
-
get_tail(n=10, raw=True, output=False, include_latest=False)[source][source]¶ Get the last n lines from the history database.
- Parameters
n (int) – The number of lines to get
raw (bool) – See
get_range()output (bool) – See
get_range()include_latest (bool) – If False (default), n+1 lines are fetched, and the latest one is discarded. This is intended to be used where the function is called by a user command, which it should not return.
- Returns
- Return type
Tuples as
get_range()
-
-
stream_logger(logger, log_level=20, msg_format=None)[source][source]¶ Set up a
logging.Loggerinstance, add a stream handler.Should do some validation on the log level there. There’s a really useful block of code in the tutorial.
- Parameters
- Returns
logger – Defaults to
logging.INFOand ‘%(asctime)s : %(levelname)s : %(message)s : ‘- Return type
logging.Logger()instance
Examples
>>> import logging >>> from default_profile.startup.file_logger import stream_logger >>> LOGGER = stream_logger(logging.getLogger(name=__name__))