Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""
Write a line to a file.
:param filename: Path of file to write to, either absolute or relative to
the dir set by set_log_file_dir().
:param line: Line to write.
"""
global _open_log_files, _log_file_dir, _log_lock
if not _acquire_lock(_log_lock):
raise LogLockError("Could not acquire exclusive lock to access"
" _open_log_files")
log_file = get_log_filename(filename)
base_file = os.path.basename(log_file)
try:
if base_file not in _open_log_files:
# First, let's close the log files opened in old directories
close_log_file(base_file)
# Then, let's open the new file
try:
os.makedirs(os.path.dirname(log_file))
except OSError:
pass
_open_log_files[base_file] = open(log_file, "w")
timestr = time.strftime("%Y-%m-%d %H:%M:%S")
try:
line = string_safe_encode(line)
except UnicodeDecodeError:
line = line.decode("utf-8", "ignore").encode("utf-8")
_open_log_files[base_file].write("%s: %s\n" % (timestr, line))
_open_log_files[base_file].flush()
finally:
def close_log_file(filename):
global _open_log_files, _log_file_dir, _log_lock
remove = []
if not _acquire_lock(_log_lock):
raise LogLockError("Could not acquire exclusive lock to access"
" _open_log_files")
try:
for k in _open_log_files:
if os.path.basename(k) == filename:
f = _open_log_files[k]
f.close()
remove.append(k)
if remove:
for key_to_remove in remove:
_open_log_files.pop(key_to_remove)
finally:
_log_lock.release()