A handler class which writes formatted logging records to disk files.
| 1188 | |
| 1189 | |
| 1190 | class FileHandler(StreamHandler): |
| 1191 | """ |
| 1192 | A handler class which writes formatted logging records to disk files. |
| 1193 | """ |
| 1194 | def __init__(self, filename, mode='a', encoding=None, delay=False, errors=None): |
| 1195 | """ |
| 1196 | Open the specified file and use it as the stream for logging. |
| 1197 | """ |
| 1198 | # Issue #27493: add support for Path objects to be passed in |
| 1199 | filename = os.fspath(filename) |
| 1200 | #keep the absolute path, otherwise derived classes which use this |
| 1201 | #may come a cropper when the current directory changes |
| 1202 | self.baseFilename = os.path.abspath(filename) |
| 1203 | self.mode = mode |
| 1204 | self.encoding = encoding |
| 1205 | if "b" not in mode: |
| 1206 | self.encoding = io.text_encoding(encoding) |
| 1207 | self.errors = errors |
| 1208 | self.delay = delay |
| 1209 | # bpo-26789: FileHandler keeps a reference to the builtin open() |
| 1210 | # function to be able to open or reopen the file during Python |
| 1211 | # finalization. |
| 1212 | self._builtin_open = open |
| 1213 | if delay: |
| 1214 | #We don't open the stream, but we still need to call the |
| 1215 | #Handler constructor to set level, formatter, lock etc. |
| 1216 | Handler.__init__(self) |
| 1217 | self.stream = None |
| 1218 | else: |
| 1219 | StreamHandler.__init__(self, self._open()) |
| 1220 | |
| 1221 | def close(self): |
| 1222 | """ |
| 1223 | Closes the stream. |
| 1224 | """ |
| 1225 | with self.lock: |
| 1226 | try: |
| 1227 | if self.stream: |
| 1228 | try: |
| 1229 | self.flush() |
| 1230 | finally: |
| 1231 | stream = self.stream |
| 1232 | self.stream = None |
| 1233 | if hasattr(stream, "close"): |
| 1234 | stream.close() |
| 1235 | finally: |
| 1236 | # Issue #19523: call unconditionally to |
| 1237 | # prevent a handler leak when delay is set |
| 1238 | # Also see Issue #42378: we also rely on |
| 1239 | # self._closed being set to True there |
| 1240 | StreamHandler.close(self) |
| 1241 | |
| 1242 | def _open(self): |
| 1243 | """ |
| 1244 | Open the current base file with the (original) mode and encoding. |
| 1245 | Return the resulting stream. |
| 1246 | """ |
| 1247 | open_func = self._builtin_open |