-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsymlink_file_handler.py
More file actions
58 lines (43 loc) · 1.76 KB
/
Copy pathsymlink_file_handler.py
File metadata and controls
58 lines (43 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import logging
from pathlib import Path
from typing import Any
__all__ = ["SymlinkFileHandler"]
log = logging.getLogger(__name__)
class SymlinkFileHandler(logging.FileHandler):
def __init__(
self,
filename: str,
log_links_dir: str,
symlink_filename: str,
*args: Any,
**kwargs: Any,
) -> None:
self.log_links_dir = Path(log_links_dir)
self.symlink_filename = symlink_filename
super().__init__(filename, *args, **kwargs)
try:
self.log_links_dir.mkdir(parents=True, exist_ok=True)
log.debug("Ensured symlink directory exists: %s", self.log_links_dir)
except (OSError, PermissionError) as e:
log.error("Failed to create symlink directory %s: %s", self.log_links_dir, e, exc_info=True)
return
target = Path(self.baseFilename).resolve()
# Timestamped symlink
named_link = self.log_links_dir / self.symlink_filename
self._create_file_symlink(target, named_link)
# Latest symlink
self._create_file_symlink(target, self.log_links_dir / "latest.log")
@staticmethod
def _create_file_symlink(target: Path, symlink_path: Path) -> None:
if not target.exists():
log.error("Target for symlink does not exist: %s", target)
return
tmp = symlink_path.with_suffix(symlink_path.suffix + ".tmp")
try:
if tmp.exists() or tmp.is_symlink():
tmp.unlink()
tmp.symlink_to(target)
tmp.replace(symlink_path)
log.info("Created symlink %s -> %s", symlink_path, target)
except (OSError, PermissionError) as e:
log.error("Failed to create symlink %s: %s", symlink_path, e, exc_info=True)