logging in a cmd2 application #1248
-
Is there a way to log everything done on a cmd2 application by also redirecting the I am using Basically i am looking to see if
|
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 4 replies
-
You can use cmd2 to create transcripts in 2 ways. The first is with the history command using its --transcript option. It runs specified commands from your history and writes a transcript file with prompt and output. Here are the basic steps. Run commands to put them in your history
Run history to identify the command numbers you want included in the transcript.
Create the transcript file
The second way to do this is with the run_script command.
Let me know if you have any more questions. |
Beta Was this translation helpful? Give feedback.
-
I don't have an easy answer to that. The first thing that comes to mind is using tee. The issue with that approach is you won't have any of the nice readline features like tab completion, up arrow history, etc. |
Beta Was this translation helpful? Give feedback.
-
Nevermind about using tee. That won't capture the typed command. |
Beta Was this translation helpful? Give feedback.
-
Now that i think about it.Even with a i think logfile should be an argument while initializing the
|
Beta Was this translation helpful? Give feedback.
-
Here is a possible solution. It uses a import logging
from typing import (
Any,
)
from cmd2 import (
cmd2,
)
class MyApp(cmd2.Cmd):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.register_postparsing_hook(self._postparsing_hook)
# Write logs to a file and don't include the log tags.
logging.basicConfig(filename='log.txt', format='%(message)s', encoding='utf-8', level=logging.INFO)
def _postparsing_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
"""Log the prompt and typed command. This runs right after the command line is parsed."""
# Handle multiline commands by restoring continuation_prompts
command_line = data.statement.raw.replace("\n", f"\n{self.continuation_prompt}")
logging.info(f"{self.prompt}{command_line}")
return data
def poutput(self, msg: Any = '', *, end: str = '\n') -> None:
"""Override poutput() to log all data before calling the parent"""
# Remove ansi style characters (e.g. color) which we don't want in the log file
# This originally was "{msg}{end}", but that printed too many newlines in the log file.
# So you might want to mess with the formatting to fit your preference.
to_log = cmd2.ansi.strip_style(f"{msg}")
logging.info(to_log)
super().poutput(msg, end=end) |
Beta Was this translation helpful? Give feedback.
Here is a possible solution. It uses a
cmd2
postparsing hook to log each command line. And then it overridesself.poutput()
to write all output to your log file before its printed.