-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChronoLog.py
More file actions
128 lines (106 loc) · 4.05 KB
/
ChronoLog.py
File metadata and controls
128 lines (106 loc) · 4.05 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import os
import time
import logging
from ftplib import FTP
from datetime import datetime
# -----------------------------
# CONFIGURATION
# -----------------------------
SOURCE_FILE = r"C:\path\to\Sensor_Log.txt" # Log file generated by Server
ARCHIVE_DIR = r"C:\LogsArchive" # Local archive folder
LOG_FILE = r"C:\LogsArchive\transfer_log.txt" # Local log file
CHECK_INTERVAL = 10 # Seconds to check if file was updated
# History Server (stores all archived logs)
HISTORY_SERVER = {
"host": "192.168.X.X", # Replace with History server IP
"user": "your_user",
"passwd": "your_password",
"dir": "/history_logs"
}
# DM Server (always gets latest log only)
DM_SERVER = {
"host": "192.168.X.X", # Replace with DM server IP
"user": "your_user",
"passwd": "your_password",
"dir": "/dm_latest"
}
# -----------------------------
# LOGGING CONFIGURATION
# -----------------------------
os.makedirs(ARCHIVE_DIR, exist_ok=True)
logging.basicConfig(
filename=LOG_FILE,
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
# -----------------------------
# FTP UPLOAD FUNCTION
# -----------------------------
def ftp_upload(server, filepath, filename):
try:
with FTP(server["host"]) as ftp:
ftp.login(server["user"], server["passwd"])
ftp.cwd(server["dir"])
with open(filepath, "rb") as f:
ftp.storbinary(f"STOR {filename}", f)
logging.info(f"Uploaded {filename} to {server['host']}")
print(f"[✔] Uploaded {filename} to {server['host']}")
except Exception as e:
logging.error(f"FTP upload failed to {server['host']}: {e}")
print(f"[✖] FTP upload failed to {server['host']}: {e}")
# -----------------------------
# PROCESS FILE (Update timestamp inside content)
# -----------------------------
def process_file(src_path, archive_dir):
if not os.path.exists(src_path):
logging.warning("Source file not found.")
print("[!] Source file not found.")
return None
with open(src_path, "r") as f:
lines = f.readlines()
# Add current timestamp to each line
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
lines = [f"{line.strip()} | {timestamp}\n" for line in lines]
# Create archive filename
archive_filename = f"ValueLog_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
archive_path = os.path.join(archive_dir, archive_filename)
# Save processed file
with open(archive_path, "w") as f:
f.writelines(lines)
logging.info(f"Processed & archived file: {archive_filename}")
print(f"[✔] Processed & archived file: {archive_filename}")
return archive_path, archive_filename
# -----------------------------
# MAIN MONITORING LOOP
# -----------------------------
def main():
print("[⏳] Monitoring started. Waiting for file updates...")
logging.info("Monitoring started.")
last_mtime = None
while True:
try:
if os.path.exists(SOURCE_FILE):
mtime = os.path.getmtime(SOURCE_FILE)
# Detect file change
if last_mtime is None or mtime != last_mtime:
last_mtime = mtime
# Step 1: Process and archive
result = process_file(SOURCE_FILE, ARCHIVE_DIR)
if not result:
continue
archive_path, archive_filename = result
# Step 2: Upload full archive to History Server
ftp_upload(HISTORY_SERVER, archive_path, archive_filename)
# Step 3: Upload latest log to FDM Server
ftp_upload(DM_SERVER, archive_path, "Server_Log_latest.txt")
time.sleep(CHECK_INTERVAL)
except Exception as e:
logging.error(f"Error: {e}")
print(f"[✖] Error: {e}")
time.sleep(CHECK_INTERVAL)
# -----------------------------
# ENTRY POINT
# -----------------------------
if __name__ == "__main__":
main()