Skip to content

logging in a cmd2 application #1248

Answered by kmvanbrunt
rADikal8e7 asked this question in Q&A
Discussion options

You must be logged in to vote

Here is a possible solution. It uses a cmd2 postparsing hook to log each command line. And then it overrides self.poutput() to write all output to your log file before its printed.

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.Po…

Replies: 5 comments 4 replies

Comment options

You must be logged in to vote
1 reply
@rADikal8e7
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@rADikal8e7
Comment options

Comment options

You must be logged in to vote
2 replies
@kmvanbrunt
Comment options

@rADikal8e7
Comment options

Answer selected by rADikal8e7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants