Skip to content

Commit eac6526

Browse files
committed
Improve logging output
1 parent e355922 commit eac6526

File tree

3 files changed

+28
-20
lines changed

3 files changed

+28
-20
lines changed

main.py

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import re
1+
import logging
22
import subprocess
33
import os
44
import datetime
@@ -11,12 +11,18 @@
1111
from src import settings
1212
from src import docker
1313

14+
# Read config and setup logging
1415
config, global_labels = settings.read()
16+
logging.basicConfig(
17+
level=config.loglevel,
18+
format='%(asctime)s %(levelname)s %(message)s'
19+
)
20+
logging.info("Starting backup service")
21+
22+
# Connecting to docker API
1523
docker_client = docker.get_client()
1624
own_container = docker.get_own_container(docker_client)
17-
18-
if config.verbose:
19-
print(f"VERBOSE: Own Container ID: {own_container.id}")
25+
logging.debug(f"Own Container ID: {own_container.id}")
2026

2127
while True:
2228
containers = docker_client.containers.list(
@@ -27,29 +33,28 @@
2733

2834
if len(containers):
2935
successful_containers = 0
30-
print(f"Starting backup cycle with {len(containers)} container(s)..")
36+
logging.info(f"Starting backup cycle with {len(containers)} container(s)..")
3137

3238
network = docker_client.networks.create("docker-database-backup")
3339
network.connect(own_container.id)
3440

3541
for i, container in enumerate(containers):
3642
database = Database(container, global_labels)
3743

38-
print("[{}/{}] Processing container {} {} ({})".format(
44+
logging.info("[{}/{}] Processing container {} {} ({})".format(
3945
i + 1,
4046
len(containers),
4147
container.short_id,
4248
container.name,
4349
database.type.name
4450
))
4551

46-
if config.verbose:
47-
print("VERBOSE: Login {}@host:{} using Password: {}".format(database.username, database.port, "YES" if len(database.password) > 0 else "NO"))
48-
if database.compress:
49-
print("VERBOSE: Compressing backup")
52+
logging.debug("Login {}@host:{} using Password: {}".format(database.username, database.port, "YES" if len(database.password) > 0 else "NO"))
53+
if database.compress:
54+
logging.debug("Compressing backup")
5055

5156
if database.type == DatabaseType.unknown:
52-
print("Cannot read database type. Please specify via label.")
57+
logging.info("Cannot read database type. Please specify via label.")
5358

5459
network.connect(container, aliases = ["database-backup-target"])
5560
outFile = "/dump/{}.sql".format(container.name)
@@ -94,8 +99,8 @@
9499
network.disconnect(container)
95100

96101
if error_code > 0:
97-
print(f"FAILED. Return Code: {error_code}; Error Output:")
98-
print(f"{error_text}")
102+
logging.error(f"FAILED. Return Code: {error_code}; Error Output:")
103+
logging.error(f"{error_text}")
99104
else:
100105
if (os.path.exists(outFile)):
101106
uncompressed_size = os.path.getsize(outFile)
@@ -111,17 +116,17 @@
111116
os.chown(outFile, config.dump_uid, config.dump_gid) # pylint: disable=maybe-no-member
112117

113118
successful_containers += 1
114-
print("SUCCESS. Size: {}{}".format(humanize.naturalsize(uncompressed_size), " (" + humanize.naturalsize(compressed_size) + " compressed)" if database.compress else ""))
119+
logging.info("SUCCESS. Size: {}{}".format(humanize.naturalsize(uncompressed_size), " (" + humanize.naturalsize(compressed_size) + " compressed)" if database.compress else ""))
115120

116121
network.disconnect(own_container.id)
117122
network.remove()
118-
print(f"Finished backup cycle. {successful_containers}/{len(containers)} successful.")
123+
logging.info(f"Finished backup cycle. {successful_containers}/{len(containers)} successful.")
119124
else:
120-
print("No databases to backup")
125+
logging.info("No databases to backup")
121126

122127
if config.interval > 0:
123128
nextRun = datetime.datetime.now() + datetime.timedelta(seconds=config.interval)
124-
print("Scheduled next run at {}..".format(nextRun.strftime("%Y-%m-%d %H:%M:%S")))
129+
logging.info("Scheduled next run at {}..".format(nextRun.strftime("%Y-%m-%d %H:%M:%S")))
125130

126131
time.sleep(config.interval)
127132
else:

src/docker.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
import os
23
import sys
34

@@ -8,7 +9,7 @@
89

910
def get_client():
1011
if not os.path.exists(DOCKER_SOCK):
11-
print(f"ERROR: Docker Socket not found. Socket file must be created at {DOCKER_SOCK}")
12+
logging.error(f"Docker Socket not found. Socket file must be created at {DOCKER_SOCK}")
1213
sys.exit(1)
1314

1415
return docker.from_env()
@@ -22,10 +23,10 @@ def get_own_container(docker_client):
2223
)
2324

2425
if len(containers) == 0:
25-
print("ERROR: Cannot determine own container id!")
26+
logging.error("Cannot determine own container id!")
2627
sys.exit(1)
2728
elif len(containers) > 1:
28-
print("ERROR: Detected another instance of this image. Running multiple instances of the backup service is currently not supported!")
29+
logging.error("Detected another instance of this image. Running multiple instances of the backup service is currently not supported!")
2930
sys.exit(1)
3031

3132
return containers[0]

src/settings.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
import os
23
import distutils.util
34

@@ -26,6 +27,7 @@ def __init__(self, values):
2627
raise AttributeError("Interval must be positive")
2728

2829
self.verbose = distutils.util.strtobool(values["verbose"])
30+
self.loglevel = logging.DEBUG if self.verbose else logging.INFO
2931

3032
self.dump_uid = int(values["dump_uid"])
3133
self.dump_gid = int(values["dump_gid"])

0 commit comments

Comments
 (0)