Ausgaben in eine Log-Datei speichern
Im folgenden Python-Skript wird beispielhaft gezeigt wie Sie mit Python in eine Log-Datei schreiben können. Dazu dient hier die Funktion log(), welcher einfach die gewünschte Log-Meldung übergeben wird. Die Funktion öffnet anschließend die über logfile spezifizierte Log-Datei und fügt die Log-Meldung mit einem Zeitstempel in die Log-Datei ein. Anschließend wird der Handle auf die Log-Datei wieder geschlossen.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# import required modules
import time
import sys
# path and name of the log file
logfile = '/var/log/logfile.log'
# function to save log messages to specified log file
def log(msg):
# open the specified log file
file = open(logfile,"a")
# write log message with timestamp to log file
file.write("%s: %s\n" % (time.strftime("%d.%m.%Y %H:%M:%S"), msg))
# close log file
file.close
# main function
def main():
# create new log message
log("Eine neue Nachricht für die Log-Datei")
# quit python script
sys.exit(0)
if __name__ == '__main__':
main()
# -*- coding: utf-8 -*-
# import required modules
import time
import sys
# path and name of the log file
logfile = '/var/log/logfile.log'
# function to save log messages to specified log file
def log(msg):
# open the specified log file
file = open(logfile,"a")
# write log message with timestamp to log file
file.write("%s: %s\n" % (time.strftime("%d.%m.%Y %H:%M:%S"), msg))
# close log file
file.close
# main function
def main():
# create new log message
log("Eine neue Nachricht für die Log-Datei")
# quit python script
sys.exit(0)
if __name__ == '__main__':
main()
Dieser Eintrag wurde am 18.08.2013 erstellt.
Direkter Link zu dieser Seite: http://www.gtkdb.de/index_31_2299.html
[ Zur Startseite ] [ Zur Kategorie ]
© 2004-2021 by Georg Kainzbauer