skip to Main Content

I’m NOT a programmer, but a very enthusiast user 🙂
I’ve implemented a logger with influxdb, grafana and a connection to a modbus interface via tcp/ip with python. All works well, but i have a big issue, i cannot have LOGS of the activities, maybe for the bad construct i’ve used.
Basically i should have the bot listening, and another infinite thread who pull data from an inverter.
Here is a cutted version of the construct i’ve used:

def start(update: Updater, context: CallbackContext):
    update.message.reply_text('Whatever command/action/function i want')

def anothercommand(update: Updater, context: CallbackContext):
    update.message.reply_text('Whatever command/action/function i want')

def loop(update: Updater, context: CallbackContext):
    print('Starting thread for automations')
    def thread1(update: Updater, context: CallbackContext):
        while 1:
            #loop to collect data into dB and send automated TG Alerts
            update.message.reply_text('I am from thread 1. going to sleep now.')
            time.sleep(2)
    t1 = threading.Thread(target=thread1,args=(update,context))
    t1.start()

def main() -> None:
    print('bot started..')
    updater = Updater(TOKEN,use_context=True)
    dispatcher = updater.dispatcher
    loop(updater,CallbackContext)
    dispatcher.add_handler(CommandHandler('start', start))
    dispatcher.add_handler(CommandHandler('anothercommand', anothercommand))
    updater.start_polling()
    updater.idle()
    
if __name__ == '__main__':
    main()

…forcing the logging to a file :

sys.stdout = open('/the/path/to/your/file', 'w')

or with

file.py > output.txt

or

import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)

generate an empty logfile, and nothing appears on the console. How i should figure out?

2

Answers


  1. Chosen as BEST ANSWER

    I have partially resolved...

    obviously i had inserted before code for logging, but i have simplied the code to have your opinion. Now i'm logging into a file (and see also logs on the console), but it don't catch all exeptions...

    With a function (like "anothercommand"), who calls a second one (gpio setup for automation), i have an error logged to the console, but NOT in the file (related to an OUT assignment on an already assigned gpio pin).

    Here is the code i'm running, outside the main def:

    # create logger
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')
    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.setLevel(logging.DEBUG)
    stdout_handler.setFormatter(formatter)
    file_handler = logging.FileHandler('logs.log')
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    logger.addHandler(stdout_handler) 
    

  2. From your code it does not look like you write to the log.

    If you go with "import logging", you need to write to the log like this:

    logging.warning("What you need to log") # this will be level warning in the log
    logging.debug("What you need to log") # this will be level debug in the log
    logging.error("What you need to log") # this will be level error in the log
    ... #other logging levels
    

    In the basicConfig you set the lever of what logs you to see in the example.log file

    You can see the log level here: https://docs.python.org/3/library/logging.html#logging-levels

    With logging:

    import logging
    
        
    def start(update: Updater, context: CallbackContext):
        logging.debug("Start")
        update.message.reply_text('Whatever command/action/function i want')
        
    def anothercommand(update: Updater, context: CallbackContext):
        logging.debug("Another command")
        update.message.reply_text('Whatever command/action/function i want')
    
    def loop(update: Updater, context: CallbackContext):
        print('Starting thread for automations')
        logging.debug("Starting thread for automations")
        def thread1(update: Updater, context: CallbackContext):
            while 1:
                #loop to collect data into dB and send automated TG Alerts
                update.message.reply_text('I am from thread 1. going to sleep now.')
                time.sleep(2)
        t1 = threading.Thread(target=thread1,args=(update,context))
        t1.start()
    
    def main() -> None:
        print('bot started..')
        logging.debug("Bot started..")
        updater = Updater(TOKEN,use_context=True)
        dispatcher = updater.dispatcher
        loop(updater,CallbackContext)
        dispatcher.add_handler(CommandHandler('start', start))
        dispatcher.add_handler(CommandHandler('anothercommand', anothercommand))
        updater.start_polling()
        updater.idle()
        
    if __name__ == '__main__':
        logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
        main()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search