-
Notifications
You must be signed in to change notification settings - Fork 12
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
Dudnik-Denys
wants to merge
3
commits into
alex-pancho:after_lession
Choose a base branch
from
Dudnik-Denys:hw_data
base: after_lession
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Hw_data_Dudnik #78
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | ||
|
||
# Після того як ми прочитали потрібні нам дані і зберегли їх - порахуємо різницю наступного і початкового рядку | ||
# (виключаючи останній рядок, щоб не вийти за межі списку, адже його різниця з минулим і так порахується) | ||
# і те чи виходять вони за певні межі часу і в залежності від цього будем логувати варнінг чи ерор. | ||
|
||
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}') | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ок гугль, як потім з логу зрозуміти коли сталася ця різниця? (те ж з ерором) There was a problem hiding this comment. Choose a reason for hiding this commentThe 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}') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
загальний недолік вашого підходу - робота зі строкою методами строки, хоч це і звучить парадоксально, але рядок у лозі - явний дікт, тому json
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Так, теж писав за це у коментарі, я можу ковертнути у словник і зробити у вигляді json але це буде ще один цикл, тобто буде більш вимогливим ніж це рішення, але я розумію про що Ви, у вигляді json теж здається мені більш загальним методом.