1

Is there a way to only create log file if something got logged? My program seems to create the log file even if nothing was logged.

import logging

logfilePath = "mylog.log"
logging.basicConfig(filename=logfilePath, level=logging.INFO, format='%(asctime)s: %(message)s')

myfunc1thatmightuseslog()
myfunc2thatmightuseslog()
7
  • Where are you using the actual log Commented Mar 12, 2021 at 20:33
  • I am using in different functions but I want to set up the log but not create file until I use it Commented Mar 12, 2021 at 20:35
  • Why though? A log should be a record of a run; if nothing occurred you might want to know that. Commented Mar 12, 2021 at 20:40
  • 2
    because if I see the file I can know something is wrong Commented Mar 12, 2021 at 20:40
  • Does this answer your question? Delete log file if it is empty after being closed Commented Mar 12, 2021 at 20:43

1 Answer 1

1

File handlers and subclasses all accept a delay keyword (docs):

class logging.FileHandler(filename, mode='a', encoding=None, delay=False, errors=None)

Returns a new instance of the FileHandler class. The specified file is opened and used as the stream for logging. If mode is not specified, 'a' is used. If encoding is not None, it is used to open the file with that encoding. If delay is true, then file opening is deferred until the first call to emit(). By default, the file grows indefinitely. If errors is specified, it’s used to determine how encoding errors are handled.

However, this option is not plumbed through to basicConfig, so it will always take the default value False in that case. Instead of using the basicConfig convenience, you'll want to configure logging explicitly in order to use this feature.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.