233 lines
7.2 KiB
Python
233 lines
7.2 KiB
Python
#!/usr/bin/python
|
|
# -*- coding: utf-8 -*-
|
|
# test log + gestione conf
|
|
#---------------------------------------------------------------
|
|
|
|
import time
|
|
import sys
|
|
import urllib
|
|
import os, sys
|
|
import threading
|
|
import logging
|
|
import logging.handlers
|
|
import configparser
|
|
import json
|
|
import redis
|
|
|
|
from datetime import datetime
|
|
from array import *
|
|
from logging.handlers import RotatingFileHandler
|
|
|
|
#--------------------------------------------------------------
|
|
# Classe helper x pubblicazione stato vero IOB-MAN
|
|
#--------------------------------------------------------------
|
|
class IobWinStatus:
|
|
def toJSON(self):
|
|
return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True)
|
|
#stream = 'cse' # Class Variable
|
|
def __init__(self,codIob,iobType):
|
|
self.CodIob = codIob
|
|
self.IobType = iobType
|
|
self.counterIOB = 0
|
|
self.counterMAC = 0
|
|
self.freeNotes = ''
|
|
self.lastDataIn = ''
|
|
self.lastDataOut = ''
|
|
self.lastUpdate = ''
|
|
self.online = False
|
|
self.queueAlLen = 0
|
|
self.queueEvLen = 0
|
|
self.queueFlLen = 0
|
|
self.queueMsLen = 0
|
|
self.queueRawTransfLen = 0
|
|
self.queueUlLen = 0
|
|
self.semIn = 'ND'
|
|
self.semOut = 'ND'
|
|
|
|
#--------------------------------------------------------------
|
|
# COSTANTI
|
|
#--------------------------------------------------------------
|
|
MAY_LOG_FILE = 30
|
|
SAMPLETIME = 0.1
|
|
LOGFILE = 'logfile.log'
|
|
LOGLEVEL = 1
|
|
PROGRAM_NAME= 'TEST LOG'
|
|
IOB_NAME='IOB'
|
|
IOB_CONF='IOB.cfg'
|
|
MAX_LOG_SIZE = 1024 * 16
|
|
NUM_LOG_RETAIN = 5
|
|
REDIS_HOST = '127.0.0.1'
|
|
REDIS_PORT = 6379
|
|
REDIS_DB = 0
|
|
BASE_PATH = 'c:\\Steamware'
|
|
BASE_LOG_PATH = 'c:\\Steamware\\logs'
|
|
|
|
#---------------------------------------------------------------
|
|
# funzione timer thread
|
|
#---------------------------------------------------------------
|
|
def do_every (interval, worker_func, iterations = 0):
|
|
if iterations != 1:
|
|
threading.Timer (
|
|
interval,
|
|
do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1]
|
|
).start ();
|
|
|
|
worker_func ();
|
|
|
|
|
|
#---------------------------------------------------------------
|
|
# funzione verifica LOG
|
|
#---------------------------------------------------------------
|
|
def checkLog():
|
|
global LOGFILE
|
|
|
|
try:
|
|
# verifico logfile...
|
|
logPro.info("verifica log")
|
|
|
|
except Exception as exc :
|
|
sys.stdout.write ( '\n errore in checkLog \n\n' )
|
|
|
|
|
|
#---------------------------------------------------------------
|
|
# funzione WatchDog verso REDIS
|
|
#---------------------------------------------------------------
|
|
def sendWatchDog():
|
|
# invio su redis stato
|
|
adesso = datetime.now()
|
|
redIobMan.lastUpdate=adesso.strftime("%Y-%m-%d %H:%M:%S")
|
|
redIobMan.lastDataIn=adesso.strftime("%Y-%m-%d %H:%M:%S")
|
|
redIobMan.lastDataOut=adesso.strftime("%Y-%m-%d %H:%M:%S")
|
|
# verificare sia DAVVERO online...
|
|
redIobMan.online = True
|
|
rawVal = redIobMan.toJSON()
|
|
redSrv0.set(f'IOB-WIN-PSER-TEST:IOB:{IOB_NAME}', rawVal)
|
|
# redSrv0.set(f'Python:IobWinStatus:{IOB_CONF}', adesso.strftime("%H:%M:%S"))
|
|
logSnd.debug('Invio a REDIS segnale watchdog')
|
|
|
|
#----------------------------------------------------------------------
|
|
# Setup
|
|
#----------------------------------------------------------------------
|
|
try:
|
|
print("----------------------------")
|
|
print("Setup")
|
|
print("----------------------------")
|
|
|
|
# inizio con parse dei parametri... se li ho sono in esecuzione interattiva, imposto BASE_PATH di conseguenza
|
|
if len(sys.argv) > 1:
|
|
IOB_NAME = sys.argv[1]
|
|
# calcolo PATH esecuzione x versione COMPILATA
|
|
exe = sys.executable
|
|
BASE_PATH = os.path.dirname(exe) + '\\'
|
|
else:
|
|
# calcolo PATH esecuzione x versione INTERPRETATA
|
|
BASE_PATH = os.path.dirname(__file__) + '\\'
|
|
|
|
print(f'Iob name: {IOB_NAME}')
|
|
# fix config
|
|
IOB_CONF = f'{IOB_NAME}.cfg'
|
|
print(f'BasePath: {BASE_PATH}')
|
|
BASE_LOG_PATH = BASE_PATH + 'logs\\'
|
|
print(f'LogPath: {BASE_LOG_PATH}')
|
|
|
|
config = configparser.ConfigParser()
|
|
confFilePath = os.path.join(BASE_PATH, 'CONF', IOB_CONF)
|
|
config.read(confFilePath)
|
|
# lettura parametri
|
|
#LOGFILE = config.get('log','LOGFILE')
|
|
#LOGLEVEL = config.getint('log','LOGLEVEL')
|
|
SAMPLETIME = config.getfloat('time','SAMPLETIME')
|
|
#MAX_LOG_SIZE = config.getint('log','MAX_LOG_SIZE')
|
|
NUM_LOG_RETAIN = config.getint('log','NUM_LOG_RETAIN')
|
|
REDIS_HOST = config.get('redis','REDIS_HOST')
|
|
REDIS_PORT = config.getint('redis','REDIS_PORT')
|
|
REDIS_DB = config.getint('redis','REDIS_DB')
|
|
|
|
# fix cartella log...
|
|
BASE_LOG_PATH = os.path.join(BASE_PATH, 'logs', IOB_NAME)
|
|
logPath = os.path.join(BASE_LOG_PATH, LOGFILE)
|
|
logDirOk=os.path.exists(logPath)
|
|
if(not logDirOk):
|
|
os.makedirs(os.path.dirname(logPath), exist_ok=True)
|
|
|
|
print(f'Config file: {confFilePath}')
|
|
|
|
# setup redis...
|
|
redSrv0 = redis.Redis(
|
|
host=REDIS_HOST,
|
|
port=REDIS_PORT,
|
|
db=REDIS_DB)
|
|
|
|
print(f'REDIS_HOST: {REDIS_HOST}')
|
|
print(f'REDIS_PORT: {REDIS_PORT}')
|
|
print(f'REDIS_DB: {REDIS_DB}')
|
|
print(f'LogFile: {logPath}')
|
|
|
|
# setup oggetto comunicazione redis...
|
|
redIobMan = IobWinStatus(IOB_NAME,'IOB-WIN-PSER-TEST')
|
|
|
|
|
|
except Exception as exc :
|
|
print (PROGRAM_NAME + ' - Exception in config file \n\n' + str(exc) + '\n-- EXIT --')
|
|
sys.exit(0)
|
|
|
|
|
|
|
|
#--------------------------------------------
|
|
# Oggetto Logger
|
|
#--------------------------------------------
|
|
try:
|
|
print(f'Log setup starting...')
|
|
|
|
logPath = os.path.join(BASE_LOG_PATH, LOGFILE)
|
|
cLogLevel = logging.DEBUG
|
|
|
|
if LOGLEVEL > 10:
|
|
cLogLevel = logging.WARN
|
|
elif LOGLEVEL > 5:
|
|
cLogLevel = logging.INFO
|
|
|
|
logging.basicConfig(level=logging.DEBUG)
|
|
|
|
# add a rotating handler
|
|
handler = RotatingFileHandler(logPath,
|
|
maxBytes=MAX_LOG_SIZE,
|
|
backupCount=NUM_LOG_RETAIN
|
|
)
|
|
|
|
# Define a custom formatter
|
|
formatter = logging.Formatter('%(asctime)s %(name)-8s %(levelname)-8s %(message)s')
|
|
handler.setFormatter(formatter)
|
|
|
|
# aggiungo logger specifici (program,queue,send...)
|
|
logQue = logging.getLogger('queue')
|
|
logSnd = logging.getLogger('sendUrl')
|
|
logPro = logging.getLogger('program')
|
|
logQue.addHandler(handler)
|
|
logSnd.addHandler(handler)
|
|
logPro.addHandler(handler)
|
|
|
|
print(f'Setup completed')
|
|
print(f'----------------------------')
|
|
|
|
except Exception as exc:
|
|
# manda mail o simili - FARE!!!
|
|
print ("LOG: Impossibile creare file log con nome ")
|
|
print (LOGFILE)
|
|
#--------------------------------------------
|
|
|
|
|
|
do_every ( 0.3 , checkLog )
|
|
do_every ( 0.1 , sendWatchDog )
|
|
|
|
logPro.info( "Start " + PROGRAM_NAME )
|
|
|
|
while True :
|
|
|
|
try:
|
|
time.sleep (SAMPLETIME)
|
|
except:
|
|
logPro.error("Errore attesa SAMPLETIME")
|
|
|
|
logQue.info( "Test Scrittura | 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ | 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ | 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ | 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ" )
|