Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hw_data_Dudnik #78

Open
wants to merge 3 commits into
base: after_lession
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,7 @@ venv.bak/

# Rope project settings
.ropeproject

#logs for data hw
ideas_for_test/heartbeat/hb.log
ideas_for_test/heartbeat/hblog
36 changes: 34 additions & 2 deletions ideas_for_test/heartbeat/hb_proces.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,38 @@
from pathlib import Path
import datetime
from lession_10 import my_logger

filename = Path(__file__).parent / "hblog"
print(filename)

# Давайте порахуємо кількість варнінгів та критичних помилок
warning_count, critical_count = 0, 0

with open(filename, mode="r") as f:
lines = f.readline()

# Прочитаємо дані з файлу, нам треба лише таймстемп але ми візьмемо і ключ. Кожен новий удар закінчується на
# 0300 і починається з 0003, тому щоб зменшити об`єм файлу, та не зберігати повністю все - ми будемо брати тільки
# новий удар, тобто той рядок у якого ключ починається з 0003, це скоротить об`єм який будемо зберігати у 11 разів,
# адже новий удар наступає кожен 11-ий рядок. До того ж щоб було зручно було рахувати час ми перевернемо наш список.
# P.S. Так, можна було б для цього перетворення використати і модуль csv, але мені здається, що нащо коли можна
# обійтись без нього. До того з-за наявності оцієї частини у файлі (101, len 36) не можна її винести як
# окремий стовбець цілою. Ще можна було б потім конвертувати в словник і шукати за ключем 'Timestamp' але це ще
# одне перетворення і ще один цикл, а так я ми знаходимо 'Timestamp' у файлі і сплітуємо рядок, то знаємо, що час
# буде завжди під індексом 1.

content = [x.strip()[x.find('Timestamp'):x.find('|')].split() for x in f.readlines() if '0003' in x][::-1]

# Після того як ми прочитали потрібні нам дані і зберегли їх - порахуємо різницю наступного і початкового рядку
# (виключаючи останній рядок, щоб не вийти за межі списку, адже його різниця з минулим і так порахується)
# і те чи виходять вони за певні межі часу і в залежності від цього будем логувати варнінг чи ерор.

Copy link
Owner

@alex-pancho alex-pancho Jun 15, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

загальний недолік вашого підходу - робота зі строкою методами строки, хоч це і звучить парадоксально, але рядок у лозі - явний дікт, тому json

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Так, теж писав за це у коментарі, я можу ковертнути у словник і зробити у вигляді json але це буде ще один цикл, тобто буде більш вимогливим ніж це рішення, але я розумію про що Ви, у вигляді json теж здається мені більш загальним методом.

for i in range(len(content[:-1])):
start = datetime.datetime.strptime(content[i][1], '%H:%M:%S')
end = datetime.datetime.strptime(content[i + 1][1], '%H:%M:%S')
if datetime.timedelta(seconds=30) < end - start < datetime.timedelta(seconds=32):
my_logger.logger.warning(f'Warning! Heartbeat difference is {end - start}')
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ок гугль, як потім з логу зрозуміти коли сталася ця різниця? (те ж з ерором)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Так, тут згоден, тут треба додати час удару до логу

warning_count += 1
if datetime.timedelta(seconds=32) <= end - start:
my_logger.logger.error(f'Crtitcal! Heartbeat difference is {end - start}')
critical_count += 1

print(f'Усього варнінгів: {warning_count}', f'Усього критичних помилок: {critical_count}')
2 changes: 1 addition & 1 deletion lession_10/my_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
# logging.ERROR

# Створюємо обробник для запису в файл
file_handler = logging.FileHandler('log_file.log')
file_handler = logging.FileHandler('hb.log')
file_handler.setLevel(logging.INFO)

# Створюємо обробник для виводу в консоль
Expand Down