Home > Net >  vscode python: how to log to both file and terminal
vscode python: how to log to both file and terminal

Time:10-02

Before adding logging to my project, i would see all logs from libraries such as flask in the terminal console. After adding the following, i no longer see these output in the terminal - but they do show up in the log file. I would like to have them output to both the log file and terminal so that i can see all outputs (prints or logs) in the same terminal/console. is that possible? This is the code i used to add a logger to my app and after which i no longer see logs in the terminal window:

logging.basicConfig(filename = LOG_DIR 'app.log',
                    level = logging.WARNING,
                    format = '%(asctime)s:%(levelname)s:%(name)s:%(message)s')

logger = logging.getLogger("app_logger")
logger.setLevel(logging.INFO)

my launch.json looks like this:

    "configurations": [
        {
            "name": "Python: Flask",
            "type": "python",
            "request": "launch",
            "module": "flask",
            "env": {
                "FLASK_APP": "src/web/app.py",
                "FLASK_ENV": "development"
            },
            "args": [
                "run",
                "--no-debugger"
            ],
            "jinja": true,
            "justMyCode": true,
            "console": "integratedTerminal",
            
        },
    {
        "name": "Python: Current File",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "console": "integratedTerminal",
    }   
]

CodePudding user response:

Create an additional handler, and add it to the logger.

logging.basicConfig(filename = LOG_DIR 'app.log',
                    level = logging.WARNING,
                    format = '%(asctime)s:%(levelname)s:%(name)s:%(message)s')

logger = logging.getLogger("app_logger")
logger.setLevel(logging.INFO)

# Also log to console.
console = logging.StreamHandler()
logger.addHandler(console)

  • Related