0

I'am trying to learn about logging. When i am created my first file handler, it has worked correctly. I created a file which named "Guesses_of_PC.log" and the handler has put it to the same path with py file.

But after i want that py project in another path so i created a new folder next to the py file and put that py file to new folder and also "Guesses_of_PC.log". But now, when i run py file, it still creates "Guesses_of_PC.log" in the first directory even i wrote new path to the handler. Why it behaves like that?

Thank you for your support. Here the code:

log_guess.setLevel(logging.INFO)
log_hand_guess=logging.FileHandler(filename="Guesses_of_PC.log")
log_guess.addHandler(log_hand_guess)
log_form_guess=logging.Formatter("%(asctime)s:%(levelname)s:%(name)s:%(message)s")
log_hand_guess.setFormatter(log_form_guess) ```


  [1]: https://i.stack.imgur.com/BvUPm.png
  • Can you provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). We need how you create the log file. – yao99 Aug 08 '20 at 00:10
  • Does you run the code in the first directory? i.e. some command like: `python new_folder/code.py`. – yao99 Aug 08 '20 at 23:49
  • It seems that Python resolve the relative path base on your working directory. – yao99 Aug 09 '20 at 00:02

1 Answers1

0

Python resolve the relative path base on the working directory, and your working directory is the first directory. So it create the log file using first_folder/Guesses_of_PC.log. To create the log file in the new folder, you need to use filename="new_folder/Guesses_of_PC.log", or change the working directory before execute the code. Sample code:

log_guess.setLevel(logging.INFO)
log_hand_guess=logging.FileHandler(filename="new_folder/Guesses_of_PC.log")
log_guess.addHandler(log_hand_guess)
log_form_guess=logging.Formatter("%(asctime)s:%(levelname)s:%(name)s:%(message)s")
log_hand_guess.setFormatter(log_form_guess)
yao99
  • 870
  • 5
  • 12
  • I wrote the path before, like you said. Now it creates the log files in correct path but it says i did not find the files?! But program has created them with its own hands. You can look to the photo, i add it. Thank you for your support. I have just learnt about terms "**working directory**". – Burak Emmiler Aug 09 '20 at 12:25
  • It seems you should do the same thing when open the file since `open()` also search the working directory when finding the file. – yao99 Aug 09 '20 at 15:23