python-scripts/login-log.py
Max Fiedler 2d776b4b33 rename
2024-03-25 09:00:22 +01:00

105 lines
3.4 KiB
Python

# #!/usr/bin/env python3
"""Write information into a logfile, like the timestamp and the hostname."""
import os
import socket
from datetime import date
from datetime import datetime
# Determine if the OS is MS Windows
if os.name == 'nt':
# Set the location of the file to write to, in the user Documents directory
logfile = os.path.join(os.path.join(os.environ['USERPROFILE']),
r'Documents\login.log')
# For OS which are not MS Windows
else:
logfile = os.path.join(os.path.join(os.environ['HOME']),
r'Documents/login.log')
# Create the file if it does not exist yet
if not os.path.exists(logfile):
with open(logfile, 'w', encoding="utf-8"):
pass
# Determine the current date and time
today = date.today()
now = datetime.now()
current_day = today.strftime("%d.%m.%Y")
current_time = now.strftime("%H:%M:%S")
# Determine the client hostname
CLIENT_HOSTNAME = os.getenv("CLIENTNAME")
# Determine the client hostname via a different method
# in case the first one failed
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"
# 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', encoding="utf-8") as file:
self.__write_queue = file.readlines()
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):
return self
def __exit__(self, type, value, traceback):
if self.__write_queue:
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)
# Or, use write_lines instead - that maintains order.
# with Prepender(logfile) as f:
# f.write_lines(
# ['This will be line 1',
# 'This will be line 2',
# 'This will be line 3',
# ]
# )