@ -7,7 +7,11 @@ from max_bot.models import Client
# Папка для логов активности пользователей
LOG_DIR = os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , ' .. ' , ' log ' , ' user_activity ' )
os . makedirs ( LOG_DIR , exist_ok = True )
try :
os . makedirs ( LOG_DIR , exist_ok = True )
except Exception as e :
print ( f " ⚠️ Ошибка создания папки для логов: { e } " )
_lock = Lock ( )
@ -26,30 +30,33 @@ def log_user_action(
Логирует действие пользователя в структурированном JSON - формате .
Запись добавляется в файл user_activity_YYYY - MM - DD . log .
"""
timestamp = datetime . now ( ) . isoformat ( )
log_entry = {
" timestamp " : timestamp ,
" client_id " : client . id ,
" chat_id " : chat_id ,
" action_type " : action_type ,
" details " : details or { } ,
}
if user_query is not None :
log_entry [ " user_query " ] = user_query
if intent is not None :
log_entry [ " intent " ] = intent
if entities is not None :
log_entry [ " entities " ] = entities
if response is not None :
log_entry [ " response " ] = response
if command is not None :
log_entry [ " command " ] = command
try :
timestamp = datetime . now ( ) . isoformat ( )
log_entry = {
" timestamp " : timestamp ,
" client_id " : client . id ,
" chat_id " : chat_id ,
" action_type " : action_type ,
" details " : details or { } ,
}
if user_query is not None :
log_entry [ " user_query " ] = user_query
if intent is not None :
log_entry [ " intent " ] = intent
if entities is not None :
log_entry [ " entities " ] = entities
if response is not None :
log_entry [ " response " ] = response
if command is not None :
log_entry [ " command " ] = command
# Определяем имя файла по дате
date_str = datetime . now ( ) . strftime ( " % Y- % m- %d " )
log_file = os . path . join ( LOG_DIR , f " user_activity_ { date_str } .log " )
# Определяем имя файла по дате
date_str = datetime . now ( ) . strftime ( " % Y- % m- %d " )
log_file = os . path . join ( LOG_DIR , f " user_activity_ { date_str } .log " )
# Потокобезопасная запись
with _lock :
with open ( log_file , ' a ' , encoding = ' utf-8 ' ) as f :
f . write ( json . dumps ( log_entry , ensure_ascii = False ) + ' \n ' )
# Потокобезопасная запись
with _lock :
with open ( log_file , ' a ' , encoding = ' utf-8 ' ) as f :
f . write ( json . dumps ( log_entry , ensure_ascii = False ) + ' \n ' )
except Exception as e :
print ( f " ⚠️ Ошибка записи лога: { e } " )