RotatingFileHandler with console logging












0















I've written an init function to configure the python logging module to log to a file and the console. I want to limit the log file size using the RotatingFileHandler. The code below doesn't cause any errors and does everything I want, except it doesn't rotate the logs. I set a low file size to test things out.



How can I configure to use rotating logs and the console with different formats like below?



import logging, logging.handlers

LOG_LEVEL = logging.DEBUG
CONSOLE_LEVEL = logging.DEBUG


def init_logger(fullpath, console_level=CONSOLE_LEVEL, log_level=LOG_LEVEL):
"""
Setup the logger object

Args:
fullpath (str): full path to the log file
"""
logging.basicConfig(level=LOG_LEVEL,
format='%(asctime)s %(threadName)-10s %(name)-12s %
(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S',
filename=fullpath,
filemode='w')

_logger = logging.getLogger('_root')
_logger.setLevel(log_level)

log_handler = logging.handlers.RotatingFileHandler(filename=fullpath,
maxBytes=50, backupCount=10)
log_handler.setLevel(log_level)
_logger.addHandler(log_handler)

console = logging.StreamHandler()
console.setLevel(console_level)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %
(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
logging.debug("Creating log file")









share|improve this question























  • Your logger initiation seems pretty standard and seems correct. Maybe your usage is incorrect, are you writing to logger with the name _root? If you're writing to logger without name, your log won't be rotated or written. You can have logger with more than 1 handler. Might be better if you post your usage code as well.

    – Thu Yein Tun
    Nov 25 '18 at 3:13
















0















I've written an init function to configure the python logging module to log to a file and the console. I want to limit the log file size using the RotatingFileHandler. The code below doesn't cause any errors and does everything I want, except it doesn't rotate the logs. I set a low file size to test things out.



How can I configure to use rotating logs and the console with different formats like below?



import logging, logging.handlers

LOG_LEVEL = logging.DEBUG
CONSOLE_LEVEL = logging.DEBUG


def init_logger(fullpath, console_level=CONSOLE_LEVEL, log_level=LOG_LEVEL):
"""
Setup the logger object

Args:
fullpath (str): full path to the log file
"""
logging.basicConfig(level=LOG_LEVEL,
format='%(asctime)s %(threadName)-10s %(name)-12s %
(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S',
filename=fullpath,
filemode='w')

_logger = logging.getLogger('_root')
_logger.setLevel(log_level)

log_handler = logging.handlers.RotatingFileHandler(filename=fullpath,
maxBytes=50, backupCount=10)
log_handler.setLevel(log_level)
_logger.addHandler(log_handler)

console = logging.StreamHandler()
console.setLevel(console_level)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %
(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
logging.debug("Creating log file")









share|improve this question























  • Your logger initiation seems pretty standard and seems correct. Maybe your usage is incorrect, are you writing to logger with the name _root? If you're writing to logger without name, your log won't be rotated or written. You can have logger with more than 1 handler. Might be better if you post your usage code as well.

    – Thu Yein Tun
    Nov 25 '18 at 3:13














0












0








0








I've written an init function to configure the python logging module to log to a file and the console. I want to limit the log file size using the RotatingFileHandler. The code below doesn't cause any errors and does everything I want, except it doesn't rotate the logs. I set a low file size to test things out.



How can I configure to use rotating logs and the console with different formats like below?



import logging, logging.handlers

LOG_LEVEL = logging.DEBUG
CONSOLE_LEVEL = logging.DEBUG


def init_logger(fullpath, console_level=CONSOLE_LEVEL, log_level=LOG_LEVEL):
"""
Setup the logger object

Args:
fullpath (str): full path to the log file
"""
logging.basicConfig(level=LOG_LEVEL,
format='%(asctime)s %(threadName)-10s %(name)-12s %
(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S',
filename=fullpath,
filemode='w')

_logger = logging.getLogger('_root')
_logger.setLevel(log_level)

log_handler = logging.handlers.RotatingFileHandler(filename=fullpath,
maxBytes=50, backupCount=10)
log_handler.setLevel(log_level)
_logger.addHandler(log_handler)

console = logging.StreamHandler()
console.setLevel(console_level)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %
(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
logging.debug("Creating log file")









share|improve this question














I've written an init function to configure the python logging module to log to a file and the console. I want to limit the log file size using the RotatingFileHandler. The code below doesn't cause any errors and does everything I want, except it doesn't rotate the logs. I set a low file size to test things out.



How can I configure to use rotating logs and the console with different formats like below?



import logging, logging.handlers

LOG_LEVEL = logging.DEBUG
CONSOLE_LEVEL = logging.DEBUG


def init_logger(fullpath, console_level=CONSOLE_LEVEL, log_level=LOG_LEVEL):
"""
Setup the logger object

Args:
fullpath (str): full path to the log file
"""
logging.basicConfig(level=LOG_LEVEL,
format='%(asctime)s %(threadName)-10s %(name)-12s %
(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S',
filename=fullpath,
filemode='w')

_logger = logging.getLogger('_root')
_logger.setLevel(log_level)

log_handler = logging.handlers.RotatingFileHandler(filename=fullpath,
maxBytes=50, backupCount=10)
log_handler.setLevel(log_level)
_logger.addHandler(log_handler)

console = logging.StreamHandler()
console.setLevel(console_level)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %
(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
logging.debug("Creating log file")






python






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 25 '18 at 2:15









ND24ND24

1316




1316













  • Your logger initiation seems pretty standard and seems correct. Maybe your usage is incorrect, are you writing to logger with the name _root? If you're writing to logger without name, your log won't be rotated or written. You can have logger with more than 1 handler. Might be better if you post your usage code as well.

    – Thu Yein Tun
    Nov 25 '18 at 3:13



















  • Your logger initiation seems pretty standard and seems correct. Maybe your usage is incorrect, are you writing to logger with the name _root? If you're writing to logger without name, your log won't be rotated or written. You can have logger with more than 1 handler. Might be better if you post your usage code as well.

    – Thu Yein Tun
    Nov 25 '18 at 3:13

















Your logger initiation seems pretty standard and seems correct. Maybe your usage is incorrect, are you writing to logger with the name _root? If you're writing to logger without name, your log won't be rotated or written. You can have logger with more than 1 handler. Might be better if you post your usage code as well.

– Thu Yein Tun
Nov 25 '18 at 3:13





Your logger initiation seems pretty standard and seems correct. Maybe your usage is incorrect, are you writing to logger with the name _root? If you're writing to logger without name, your log won't be rotated or written. You can have logger with more than 1 handler. Might be better if you post your usage code as well.

– Thu Yein Tun
Nov 25 '18 at 3:13












1 Answer
1






active

oldest

votes


















0














This is your logging's structure:



---root <- I mean real root, which you will get from logging.getLogger([""])
---NormalFileHandler <- Configged by logging.basicConfig, this handler won't rotate file.
---StreamHandler
------_root <- Your root logger, although I don't understand why you want this.
------RotatingFileHandler <- This one will rotate file.


And then you use logging.debug("Creating log file"), which is the same as calling debug on root logger: logging.getLogger().debug(...). So this log passed to StreamHandler and NormalFileHandler.



That's why you see the file isn't got rotated.



The correct configuration should be:



def init_logger(fullpath, console_level=CONSOLE_LEVEL, log_level=LOG_LEVEL):
"""
Setup the logger object

Args:
fullpath (str): full path to the log file
"""
logger = logging.getLogger('YourLogger')
logger.setLevel(log_level)

log_handler = logging.handlers.RotatingFileHandler(filename=fullpath,
maxBytes=50, backupCount=10)
log_handler.setLevel(log_level)
formatter = logging.Formatter('%(asctime)s %(threadName)-10s %(name)-12s %
(levelname)-8s %(message)s')
log_handler.setFormatter(formatter)
logger.addHandler(log_handler)

console = logging.StreamHandler()
console.setLevel(console_level)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %
(message)s')
console.setFormatter(formatter)
logger.addHandler(console) # Or you can add it to root logger, but it is not recommended, you should use your own logger instead of root logger. Or it will cause some problems.
logger.debug("Creating log file")


And then when you want to use logger, you should use:



logger = logging.getLogger('YourLogger')
logger.info(...)
logger.debug(...)





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53464104%2frotatingfilehandler-with-console-logging%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    This is your logging's structure:



    ---root <- I mean real root, which you will get from logging.getLogger([""])
    ---NormalFileHandler <- Configged by logging.basicConfig, this handler won't rotate file.
    ---StreamHandler
    ------_root <- Your root logger, although I don't understand why you want this.
    ------RotatingFileHandler <- This one will rotate file.


    And then you use logging.debug("Creating log file"), which is the same as calling debug on root logger: logging.getLogger().debug(...). So this log passed to StreamHandler and NormalFileHandler.



    That's why you see the file isn't got rotated.



    The correct configuration should be:



    def init_logger(fullpath, console_level=CONSOLE_LEVEL, log_level=LOG_LEVEL):
    """
    Setup the logger object

    Args:
    fullpath (str): full path to the log file
    """
    logger = logging.getLogger('YourLogger')
    logger.setLevel(log_level)

    log_handler = logging.handlers.RotatingFileHandler(filename=fullpath,
    maxBytes=50, backupCount=10)
    log_handler.setLevel(log_level)
    formatter = logging.Formatter('%(asctime)s %(threadName)-10s %(name)-12s %
    (levelname)-8s %(message)s')
    log_handler.setFormatter(formatter)
    logger.addHandler(log_handler)

    console = logging.StreamHandler()
    console.setLevel(console_level)
    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %
    (message)s')
    console.setFormatter(formatter)
    logger.addHandler(console) # Or you can add it to root logger, but it is not recommended, you should use your own logger instead of root logger. Or it will cause some problems.
    logger.debug("Creating log file")


    And then when you want to use logger, you should use:



    logger = logging.getLogger('YourLogger')
    logger.info(...)
    logger.debug(...)





    share|improve this answer




























      0














      This is your logging's structure:



      ---root <- I mean real root, which you will get from logging.getLogger([""])
      ---NormalFileHandler <- Configged by logging.basicConfig, this handler won't rotate file.
      ---StreamHandler
      ------_root <- Your root logger, although I don't understand why you want this.
      ------RotatingFileHandler <- This one will rotate file.


      And then you use logging.debug("Creating log file"), which is the same as calling debug on root logger: logging.getLogger().debug(...). So this log passed to StreamHandler and NormalFileHandler.



      That's why you see the file isn't got rotated.



      The correct configuration should be:



      def init_logger(fullpath, console_level=CONSOLE_LEVEL, log_level=LOG_LEVEL):
      """
      Setup the logger object

      Args:
      fullpath (str): full path to the log file
      """
      logger = logging.getLogger('YourLogger')
      logger.setLevel(log_level)

      log_handler = logging.handlers.RotatingFileHandler(filename=fullpath,
      maxBytes=50, backupCount=10)
      log_handler.setLevel(log_level)
      formatter = logging.Formatter('%(asctime)s %(threadName)-10s %(name)-12s %
      (levelname)-8s %(message)s')
      log_handler.setFormatter(formatter)
      logger.addHandler(log_handler)

      console = logging.StreamHandler()
      console.setLevel(console_level)
      formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %
      (message)s')
      console.setFormatter(formatter)
      logger.addHandler(console) # Or you can add it to root logger, but it is not recommended, you should use your own logger instead of root logger. Or it will cause some problems.
      logger.debug("Creating log file")


      And then when you want to use logger, you should use:



      logger = logging.getLogger('YourLogger')
      logger.info(...)
      logger.debug(...)





      share|improve this answer


























        0












        0








        0







        This is your logging's structure:



        ---root <- I mean real root, which you will get from logging.getLogger([""])
        ---NormalFileHandler <- Configged by logging.basicConfig, this handler won't rotate file.
        ---StreamHandler
        ------_root <- Your root logger, although I don't understand why you want this.
        ------RotatingFileHandler <- This one will rotate file.


        And then you use logging.debug("Creating log file"), which is the same as calling debug on root logger: logging.getLogger().debug(...). So this log passed to StreamHandler and NormalFileHandler.



        That's why you see the file isn't got rotated.



        The correct configuration should be:



        def init_logger(fullpath, console_level=CONSOLE_LEVEL, log_level=LOG_LEVEL):
        """
        Setup the logger object

        Args:
        fullpath (str): full path to the log file
        """
        logger = logging.getLogger('YourLogger')
        logger.setLevel(log_level)

        log_handler = logging.handlers.RotatingFileHandler(filename=fullpath,
        maxBytes=50, backupCount=10)
        log_handler.setLevel(log_level)
        formatter = logging.Formatter('%(asctime)s %(threadName)-10s %(name)-12s %
        (levelname)-8s %(message)s')
        log_handler.setFormatter(formatter)
        logger.addHandler(log_handler)

        console = logging.StreamHandler()
        console.setLevel(console_level)
        formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %
        (message)s')
        console.setFormatter(formatter)
        logger.addHandler(console) # Or you can add it to root logger, but it is not recommended, you should use your own logger instead of root logger. Or it will cause some problems.
        logger.debug("Creating log file")


        And then when you want to use logger, you should use:



        logger = logging.getLogger('YourLogger')
        logger.info(...)
        logger.debug(...)





        share|improve this answer













        This is your logging's structure:



        ---root <- I mean real root, which you will get from logging.getLogger([""])
        ---NormalFileHandler <- Configged by logging.basicConfig, this handler won't rotate file.
        ---StreamHandler
        ------_root <- Your root logger, although I don't understand why you want this.
        ------RotatingFileHandler <- This one will rotate file.


        And then you use logging.debug("Creating log file"), which is the same as calling debug on root logger: logging.getLogger().debug(...). So this log passed to StreamHandler and NormalFileHandler.



        That's why you see the file isn't got rotated.



        The correct configuration should be:



        def init_logger(fullpath, console_level=CONSOLE_LEVEL, log_level=LOG_LEVEL):
        """
        Setup the logger object

        Args:
        fullpath (str): full path to the log file
        """
        logger = logging.getLogger('YourLogger')
        logger.setLevel(log_level)

        log_handler = logging.handlers.RotatingFileHandler(filename=fullpath,
        maxBytes=50, backupCount=10)
        log_handler.setLevel(log_level)
        formatter = logging.Formatter('%(asctime)s %(threadName)-10s %(name)-12s %
        (levelname)-8s %(message)s')
        log_handler.setFormatter(formatter)
        logger.addHandler(log_handler)

        console = logging.StreamHandler()
        console.setLevel(console_level)
        formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %
        (message)s')
        console.setFormatter(formatter)
        logger.addHandler(console) # Or you can add it to root logger, but it is not recommended, you should use your own logger instead of root logger. Or it will cause some problems.
        logger.debug("Creating log file")


        And then when you want to use logger, you should use:



        logger = logging.getLogger('YourLogger')
        logger.info(...)
        logger.debug(...)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 25 '18 at 3:26









        SrawSraw

        7,66631439




        7,66631439
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53464104%2frotatingfilehandler-with-console-logging%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            TypeError: fit_transform() missing 1 required positional argument: 'X'