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
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:
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:
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: