[Python] Set up logging for a script or interactive session in Python

Discussão em 'Python' iniciado por Stack, Abril 18, 2025.

  1. Stack

    Stack Membro Participativo

    I want to be able to log from jupyter notebooks into stderr without writing any information about logging in jupyter notebook itself and I want to be able to log into a file when a script starts.

    By deafult, in jupyter notebook the logging is set to warning, so I need to modify it to be an info for in code.py.

    I have some code in a module:

    code.py

    import logging
    logger = logging.getLogger()

    handler = logging.StreamHandler(sys.stderr)
    if logger.level == 30:
    logger.setLevel(logging.INFO)
    logger.handlers = [handler] + logger.handlers

    def do_something_cool():
    logger.info("You are cool")


    In jupyter notebook it apperas the way I want.

    When I use this function from the script, I do following:

    my_script.py
    if __name__ == '__main__':
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    handler = logging.FileHandler(str(DIRECTORY / 'log_model_info.log'))
    logger.addHandler(handler)


    It looks like a hack for me what I do in code.py Is there a better way how to handle it?

    Continue reading...

Compartilhe esta Página