This commit is contained in:
Max Fiedler 2024-03-25 09:00:22 +01:00
parent 6cbcaa768d
commit 2d776b4b33

View File

@ -1,4 +1,5 @@
#!/usr/bin/env python3
# #!/usr/bin/env python3
"""Write information into a logfile, like the timestamp and the hostname."""
import os
import socket
@ -18,7 +19,7 @@ else:
# Create the file if it does not exist yet
if not os.path.exists(logfile):
with open(logfile, 'w'):
with open(logfile, 'w', encoding="utf-8"):
pass
# Determine the current date and time
@ -30,36 +31,49 @@ current_day = today.strftime("%d.%m.%Y")
current_time = now.strftime("%H:%M:%S")
# Determine the client hostname
client_hostname = os.getenv("CLIENTNAME")
CLIENT_HOSTNAME = os.getenv("CLIENTNAME")
# Determine the client hostname via a different method
# in case the first one failed
if client_hostname is None:
client_hostname = socket.gethostbyaddr(socket.gethostname())[0]
if CLIENT_HOSTNAME is None:
try:
CLIENT_HOSTNAME = socket.gethostbyaddr(socket.gethostname())[0]
except socket.herror:
print("Socket host error: unable to determine hostname.")
CLIENT_HOSTNAME = "localhost"
# Class for prepending the information to the log file
class Prepender(object):
# The `class Prepender` is a class that is used to prepend information to the
# top of a log file. It takes the file path as an argument and reads in the
# existing file. It provides methods to write lines to the file in reverse
# order, effectively prepending the lines to the top of the file. Finally,
# when the `Prepender` object is closed or exited, it writes the modified lines
# back to the file.
class Prepender:
'''Class for prepending the information to the log file.'''
def __init__(self,
file_path,
):
# Read in the existing file, so we can write it back later
with open(file_path, mode='r') as f:
self.__write_queue = f.readlines()
with open(file_path, mode='r', encoding="utf-8") as file:
self.__write_queue = file.readlines()
self.__open_file = open(file_path, mode='w')
self.__open_file = open(file_path, mode='w', encoding="utf-8")
def write_line(self, line):
'''Function for adding a new line to the file.'''
self.__write_queue.insert(0,
"%s\n" % line,
)
def write_lines(self, lines):
'''Function for adding new lines to the file.'''
lines.reverse()
for line in lines:
self.write_line(line)
def close(self):
'''Function for closing the file after use.'''
self.__exit__(None, None, None)
def __enter__(self):
@ -70,11 +84,15 @@ class Prepender(object):
self.__open_file.writelines(self.__write_queue)
self.__open_file.close()
# if isinstance(CLIENT_HOSTNAME, type) is None:
# if CLIENT_HOSTNAME == "None":
# CLIENT_HOSTNAME = "localhost"
# Prepend the determined information to the top of the log file
with Prepender(logfile) as f:
# Must write individual lines in reverse order
f.write_line(current_day+' - '+current_time+' - '+client_hostname)
f.write_line(current_day+' - '+current_time+' - '+CLIENT_HOSTNAME)
# Or, use write_lines instead - that maintains order.
# with Prepender(logfile) as f: