Python Forum
How to create a Log file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to create a Log file (/thread-25217.html)



How to create a Log file - skaailet - Mar-24-2020

Hi,
im new in this coding thing and im creating a "program" that Ping some Ip's that I have on a list
and I would like that when the program ends pinging, it saves the information/results in a eventlog file text in order to save later that info in a Table

this is the code that im using
import os
import csv
import time
import datetime
import logging

def check_ping(hostname):
    response = os.system("fping -r 10 -q " + hostname + " >/dev/null")
    if response == 0:
        check_ping = "[OK]"
    else:
        check_ping = "[Error]"
 
    return check_ping

with open('ip-source.txt') as file:
    dump = file.read()
    dump = dump.splitlines()

    
    for ip in dump:
        
        os.system('cls')
        print('Pinging now:', ip)
        print('-'*60)
        os.system('ping -n 2 {}'.format(ip))

        print('-'*60)
        time.sleep(5)
 


log = logging.getLogger('Loggername')
log.setLevel(logging.DEBUG)

# How the information is presented. You probably only want the message part, squiggly brackets included.
formatter = logging.Formatter('{message}', style="{")  

filehandler = logging.FileHandler('filename.txt', encoding='utf-8')
filehandler.setFormatter(formatter)
filehandler.setLevel(logging.DEBUG)
log.addHandler(filehandler)

ip = "192.168.100.5"
name = "LaptopEdd"

log.info(f'{time.time():<15}|IP:{ip:>15}|Equipo:{name:>5}')
log.debug('message')
# There are more iirc, like log.critical('message')