0

I'm trying to test my understanding of logging in Python but seems I'm missing something. There are two questions I have. First is when I start the program I get a message: "DeprecationWarning: the formatter module is deprecated" What does this mean? Is there a different way I'm supposed to set the formatting? Is my formatting obsolete?

The second questions is when the code is executed I see that a file is created but when I open it it's empty. I went through some of the topics here but couldn't find a solution.

I'm on a mac not sure if this makes a difference, but still.

The code:

import formatter, logging, sys

logger = logging.getLogger(__name__)
console_logging = logging.StreamHandler(sys.stdout) #Logging the messages to the console
file_logging = logging.FileHandler('log_to_file.log') #Logging the messages to a log file

formatter = logging.Formatter('%(asctime)s - %(message)s - %(levelname)s') #Formatting how the messages would look like
console_logging.setFormatter(formatter) #The format defined above is what we will see in the console
file_logging.setFormatter(formatter) #The format defined above is what we will see in the logs

logger.addHandler(console_logging)
logger.setLevel(logging.INFO) #Setting the log level (custom), so all messages with info and above will be displayed


def user_name():
    while True:
       name = input("\nEnter your username: ")
       for letter in name:
           if letter not in 'abcdefghijklmnopqrstuvwxyz':
            logger.error('Username has to contain only letters')
       name = input('\nTry again: ')
       logger.info(f'Username Entered: {name}')        
       return None

def user_password():

    while True:
        password = int(input("\nEnter account pin: "))
        while password != 1234:
            logger.error("Invalid pin.")
            password = int(input("\nTry again: "))
            logger.info(f'Username Entered: {password}')
        return None



user_name()
user_password()


gginchev
  • 19
  • 3
  • For the first part of the question, you may want to read [Deprecated meaning?](https://stackoverflow.com/q/8111774/12122460). In general, it means that the module is still there, but is not recommended anymore, and will at some point in the future be removed. – kotatsuyaki Nov 01 '22 at 09:07
  • Thanks for the information. Do you know if there is any official documentation I can https://docs.python.org/3/howto/logging-cookbook.html – gginchev Nov 01 '22 at 09:17

1 Answers1

0

I've figured it out. Seems that the logging.FileHandler is not generating any logs in the log file for some reason. I have substituted it with: "logging.basicConfig(filename='log_to_file.log', level=logging.INFO, format='{asctime} {message} {levelname}', style='{')" This worked for me and I'm now able to see log file generated along with the logs in it.

gginchev
  • 19
  • 3