1
1
# nids/logging.py
2
2
3
3
import logging
4
+ from logging .handlers import RotatingFileHandler
4
5
from scapy .all import IP , IPv6
5
6
import os
6
7
7
8
def setup_logging ():
8
- # Clear the log file if it exists
9
9
log_file = 'nids_logs.log'
10
- if os .path .exists (log_file ):
11
- with open (log_file , 'w' ):
12
- pass
13
-
10
+ max_log_size = 5 * 1024 * 1024 # 5 MB
11
+ backup_count = 3
12
+
14
13
# Setup logging configuration
15
- logging .basicConfig (filename = log_file , level = logging .INFO ,
16
- format = '%(asctime)s:%(levelname)s:%(message)s' )
14
+ handler = RotatingFileHandler (log_file , maxBytes = max_log_size , backupCount = backup_count )
15
+ logging .basicConfig (level = logging .INFO ,
16
+ format = '%(asctime)s:%(levelname)s:%(message)s' ,
17
+ handlers = [handler ])
17
18
18
19
def log_prediction (packet , prediction , original_data , traffic_type , src_ip , dst_ip ):
19
20
summary = packet .summary () if IP in packet or IPv6 in packet else "Non-IP packet"
20
21
features_str = ', ' .join ([f'{ k } : { v } ' for k , v in original_data .items ()])
21
22
log_message = f'Packet: { summary } , Prediction: { prediction .item ()} ({ traffic_type } ), Source IP: { src_ip } , Destination IP: { dst_ip } , Features: [{ features_str } ]'
22
- logging .info (log_message )
23
+ logging .info (log_message )
0 commit comments