Удаление / изменение пути к файлу журнала приводит к ошибке.Как я могу игнорировать или исправить это? - PullRequest
0 голосов
/ 10 июня 2018

Я хочу создать папку, содержащую все мои журналы с указанием даты и времени начала и конца моего скрипта в качестве заголовка.Проблема в том, что когда программа запущена, я, очевидно, не узнаю, когда скрипт остановится, пока не произойдет.Поэтому, когда сценарий заканчивается, я меняю имя папки, в которую пишу свои журналы.

Я знаю, что могу сделать это другими способами, например, просто переместить все свои журналы в папку после завершения сценария илипросто НЕ иметь папку с именем datetime, и т. д., и т. д. Но я хочу знать, как это сделать, чтобы узнать, как отлавливать подобные ошибки и как работать с регистратором.Это неправильный путь?

# Creating root logger and script logger
if logger_enabled:
    root_log_level = logging.INFO
    # Making a folder with the date as the name
    time_ran = str(datetime.datetime.now())
    log_folder = "./logs/{time_ran} (running)".format(time_ran=time_ran)
    os.mkdir(log_folder)
    # Setting up root log
    logging.basicConfig(filename=log_folder + "/root.log",
                        format="%(name)s: %(filename)s on %(lineno)d @ %(asctime)s\
                        \n\t%(levelname)s: %(message)s",
                        level=root_log_level)
    # Other stuff
    logging.info("The log level is set at {level}".format(level=root_log_level))
    logger = logging.getLogger(__name__)
    print("\033[33mLogger created and configured\033[0m")

def exit_function():
    if logger_enabled:
        exit_time = datetime.datetime.now()
        # This try/except doesn't work. This renaming throws an error because the logger's old file path ceases to exist (because I change the name)
        try:
            # Renaming folder to contain the start and end time of the script
            os.rename(log_folder,
                        "./logs/{time_ran} to {exit_time}".format(time_ran=time_ran, exit_time=exit_time))
        except FileNotFoundError:
            pass

atexit.register(exit_function)

Вот ошибка:

Exception ignored in: <bound method Task.__del__ of <Task finished coro=<_run_event() done, defined at /usr/local/lib/python3.5/dist-packages/discord/client.py:304> exception=SystemExit('Stop command run',)>>
Traceback (most recent call last):
  File "/usr/lib/python3.5/asyncio/tasks.py", line 93, in __del__
    futures.Future.__del__(self)
  File "/usr/lib/python3.5/asyncio/futures.py", line 215, in __del__
    self._loop.call_exception_handler(context)
  File "/usr/lib/python3.5/asyncio/base_events.py", line 1177, in call_exception_handler
    exc_info=True)
  File "/usr/lib/python3.5/logging/__init__.py", line 1308, in error
    self._log(ERROR, msg, args, **kwargs)
  File "/usr/lib/python3.5/logging/__init__.py", line 1415, in _log
    self.handle(record)
  File "/usr/lib/python3.5/logging/__init__.py", line 1425, in handle
    self.callHandlers(record)
  File "/usr/lib/python3.5/logging/__init__.py", line 1487, in callHandlers
    hdlr.handle(record)
  File "/usr/lib/python3.5/logging/__init__.py", line 855, in handle
    self.emit(record)
  File "/usr/lib/python3.5/logging/__init__.py", line 1047, in emit
    self.stream = self._open()
  File "/usr/lib/python3.5/logging/__init__.py", line 1037, in _open
    return open(self.baseFilename, self.mode, encoding=self.encoding)
FileNotFoundError: [Errno 2] No such file or directory: '/home/hugernot/Desktop/PVSupportSlave/Code/logs/2018-06-09 17:50:35.563516 (running)/root.log'

Это то, к чему я стремлюсь

(Изображение папок журнала)

...