ShellLogger
- class shell_logger.ShellLogger(name, *, log_dir=None, stream_dir=None, html_file=None, indent=0, login_shell=False, log=None, init_time=None, done_time=None, duration=None)[source]
Bases:
objectRun commands in the shell, while logging various metadata.
This class will keep track of commands run in the shell, their durations, descriptions,
stdout,stderr, andreturn_code. When thefinalize()method is called, theShellLoggerobject will aggregate all the data from its commands and childShellLoggerobjects (see example below) into both JSON and HTML files.Example:
> Parent ShellLogger Object Name Duration: 18h 20m 35s > cmd1 (Click arrow '>' to expand for more details) Duration: 0.25s > Child ShellLogger Object Name (i.e. Trilinos) Duration: 3h 10m 0s > Child ShellLogger Object Name (i.e. Configure) Duration: 1m 3s > cmd1 etc...
Note
Because some
stdout/stderrstreams can be quite long, they will be written to files in a temporary directory (log_dir/tmp/YYYY-MM-DD_hh:mm:ss/). Once thefinalize()method is called, they will be aggregated in an HTML file (log_dir/html_file). The JSON file (log_dir/json_file) will contain references to thestdout/stderrfiles so that an HTML file can be recreated again later if needed.- name
The name of the
ShellLoggerobject.- Type:
- log_dir
Path to where the logs are stored for the parent
ShellLoggerand all its children.- Type:
Path
- stream_dir
Path to directory where
stdout/stderrstream logs are stored.- Type:
Path
- html_file
Path to main HTML file for the parent and child
ShellLoggerobjects.- Type:
Path
- indent
The indentation level of this
ShellLoggerobject. The parent has a level 0. Each successive child’s indent is increased by 1.- Type:
- log_book
A list containing log entries and child
ShellLoggerobjects in the order they were created.- Type:
- init_time
The time this
ShellLoggerobject was created.- Type:
datetime
- done_time
The time this
ShellLoggerobject is done with its commands/messages.- Type:
datetime
- duration
The string-formatted duration of this
ShellLogger, updated when thefinalize()method is called.- Type:
Initialize a
ShellLoggerobject.- Parameters:
name (
str) – The name to give to thisShellLoggerobject.stream_dir (
Optional[Path]) – Where thestdout/stderrstream logs are stored. This is helpful for parentShellLoggerobjects to give to childShellLoggerobjects in order to keep things in the same directory.html_file (
Optional[Path]) – The path to the main HTML file for the parent and childrenShellLoggerobjects. If omitted, this is the parentShellLoggerobject, and it will need to create the file.indent (
int) – The indentation level of thisShellLoggerobject. The parent has a level 0. Each successive child’s indent is increased by 1.login_shell (
bool) – Whether or not theShellspawned should be a login shell.log (
Optional[List[object]]) – Optionally provide an existing log list to theShellLoggerobject.init_time (
Optional[datetime]) – Optionally specify when thisShellLoggerwas initialized.done_time (
Optional[datetime]) – Optionally specify when thisShellLoggerwas finalized.duration (
Optional[str]) – A string representation of the total duration of theShellLogger.
Note
The
log,init_time,done_time, anddurationparameters are mainly used when importingShellLoggerobjects from a JSON file, and can generally be omitted.- add_child(child_name)[source]
Add a child logger.
Creates and returns a ‘child’
ShellLoggerobject. This will be one step indented in the tree of the output log (see the example in the class docstring). The total time for this child will be recorded when thefinalize()method is called in the child object.- Parameters:
child_name (
str) – The name of the childShellLoggerobject.- Returns:
A child
ShellLoggerobject.- Return type:
- static append(path)[source]
Append to a prior log.
Create a
ShellLoggerto append to the HTML log file generated by a priorShellLogger.- Parameters:
path (
Path) – The location of the priorShellLogger‘s output, either the log directory, or the HTML log file itself.- Return type:
- Returns:
A new
ShellLoggerpopulated with the data from the prior one.
- auxiliary_information()[source]
Grab auxiliary information.
Capture all sorts of auxiliary information before running a command.
- Return type:
- Returns:
The working directory, environment, umask, hostname, user, group, shell, and ulimit.
- change_log_dir(new_log_dir)[source]
Change the log directory.
Change the
log_dirof thisShellLoggerobject and all children recursively.- Parameters:
new_log_dir (Path) – Path to the new
log_dir.- Raises:
RuntimeError – If this is called on a child
ShellLogger.- Return type:
- check_duration()[source]
Get the current duration.
From the beginning of the
ShellLoggerobject’s creation until now.- Return type:
- Returns:
A string representation of the total duration.
- finalize()[source]
Finalize the
ShellLoggerobject.Write the HTML log file.
- Return type:
- html_print(msg, msg_title='HTML Message')[source]
Save a message to the log but don’t print it in the console.
- is_parent()[source]
Check whether this is a parent logger.
Determine whether or not this is the parent
ShellLoggerobject, as indicated by the object’sindentattribute.- Return type:
- Returns:
Trueif this is the parent;Falseotherwise.
- log(msg, cmd, *, cwd=None, live_stdout=False, live_stderr=False, return_info=False, verbose=False, stdin_redirect=True, **kwargs)[source]
Execute a command, and log the corresponding information.
- Parameters:
msg (
str) – A message to be recorded with the command. This could be documentation of what your command is doing and why.cmd (
str) – The shell command to be executed.live_stdout (
bool) – Printstdoutas it is being produced, as well as saving it to the file.live_stderr (
bool) – Printstderras it is being produced, as well as saving it to the file.return_info (
bool) – If set toTrue,stdout,stderr, andreturn_codewill be stored and returned in a dictionary. Consider leaving this set toFalseif you anticipate your command producing largestdout/stderrstreams that could cause memory issues.verbose (
bool) – Print the command before it is executed.stdin_redirect (
bool) – Whether or not to redirectstdinto/dev/null. We do this by default to handle issues that arise when thecmdinvolves MPI; however, in some cases (e.g., involvingbsub) the redirect causes problems, and we need the flexibility to revert back to standard behavior.**kwargs – Any other keyword arguments to pass on to
_run().
- Return type:
- Returns:
A dictionary containing
stdout,stderr,trace, andreturn_codekeys. Ifreturn_infois set toFalse, thestdoutandstderrvalues will beNone. Ifreturn_infois set toTrueandtraceis specified inkwargs,tracein the dictionary will contain the output of the specified trace; otherwise, it will beNone.
Note
To conserve memory,
stdoutandstderrwill be written to files as they are being generated.
- static strfdelta(delta, fmt)[source]
Convert a time delta to a string.
Format a time delta object. Use this like you would
datetime.strftime().
- to_html()[source]
Convert the log entries to HTML.
This method iterates through each entry in this
ShellLoggerobject’s log list and builds up a list of corresponding HTML snippets. For each entry, thestdout/stderrare copied from their respective files in thestream_dir.
- update_done_time()[source]
Update the done time.
Allows the
done_timeto be updated beforefinalize()is called. This is especially useful for childShellLoggerobjects who might finish their commands before the parent finalizes everything.- Return type:
JSON Serialization
- class shell_logger.ShellLoggerDecoder[source]
Bases:
JSONDecoderConvert JSON to
ShellLoggerobjects.This is a helper class to make the
ShellLoggerclass JSON serializable. It is used in the process of retrievingShellLoggerobjects from JSON.Usage:
import json with open('path_to_json_file', 'r') as jf: logger = json.load(jf, cls=ShellLoggerDecoder)
Initialize the decoder.
- static dict_to_object(obj)[source]
Convert a
dictto a corresponding object.This converts data dictionaries given by the JSONDecoder into objects of type
ShellLogger,datetime, etc.
Todo
Figure out why the documentation below is pulling in the docstring for the base class as well.
- class shell_logger.ShellLoggerEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]
Bases:
JSONEncoderConvert
ShellLoggerobjects to JSON.This is a helper class to make the
ShellLoggerclass JSON serializable. It is used in the process of savingShellLoggerobjects to JSON.Usage:
import json with open('path_to_json_file', 'w') as jf: json.dump(data, jf, cls=ShellLoggerEncoder)
Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.
If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.
If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an RecursionError). Otherwise, no such check takes place.
If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.
If specified, separators should be an (item_separator, key_separator) tuple. The default is (’, ‘, ‘: ‘) if indent is
Noneand (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a
TypeError.