-
Notifications
You must be signed in to change notification settings - Fork 118
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
SDK新增滚动日志功能 #700
Closed
Closed
SDK新增滚动日志功能 #700
Changes from 3 commits
Commits
Show all changes
4 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
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 |
---|---|---|
@@ -0,0 +1,111 @@ | ||
# Copyright (c) 2024 Baidu, Inc. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
import os | ||
import time | ||
import logging | ||
import unittest | ||
|
||
|
||
from appbuilder import SizeAndTimeRotatingFileHandler | ||
from appbuilder.utils.logger_util import LoggerWithLoggerId | ||
|
||
class TestLogSetLogConfig(unittest.TestCase): | ||
def test_set_log_config(self): | ||
lwl=LoggerWithLoggerId(logger='test_logger',extra={'logid':'test_logid'},loglevel='INFO') | ||
lwl.setLogConfig( | ||
console_show = True, | ||
loglevel='DEBUG', | ||
file_name='test.log', | ||
when='D', | ||
interval=0, # 测试interval<1时,自动更新为1 | ||
max_bytes=None, # 测试not max_bytes or max_bytes <= 0时,自动更新为sys.maxsize | ||
total_size_limit=None, # 测试not total_size_limit or total_size_limit <= 0时,自动更新为sys.maxsize | ||
backup_count=None, # 测试not backup_count or backup_count <= 0时,自动更新为sys.maxsize | ||
) | ||
|
||
def test_set_log_config_raise_error(self): | ||
lwl=LoggerWithLoggerId(logger='test_logger',extra={'logid':'test_logid'},loglevel='INFO') | ||
with self.assertRaises(ValueError): | ||
lwl.setLogConfig( | ||
console_show = True, | ||
loglevel='DEBUG', | ||
file_name='test.log', | ||
when='ERROR-WHEN', | ||
interval=0, # 测试interval<1时,自动更新为1 | ||
max_bytes=None, # 测试not max_bytes or max_bytes <= 0时,自动更新为sys.maxsize | ||
total_size_limit=None, # 测试not total_size_limit or total_size_limit <= 0时,自动更新为sys.maxsize | ||
backup_count=None, # 测试not backup_count or backup_count <= 0时,自动更新为sys.maxsize | ||
) | ||
|
||
def test_rolling_with_time(self): | ||
time_msgs = ['S', 'M', 'H', 'D', 'MIDNIGHT'] | ||
for time_msg in time_msgs: | ||
logger = logging.getLogger('CustomLogger') | ||
logger.setLevel(logging.DEBUG) | ||
handler = SizeAndTimeRotatingFileHandler( | ||
filename ='test.log', | ||
when=time_msg, | ||
interval=1, | ||
max_bytes=1024*100*1024, | ||
backup_count=10, | ||
total_size_limit=1024*300*1024 | ||
) | ||
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') | ||
handler.setFormatter(formatter) | ||
logger.addHandler(handler) | ||
|
||
for _ in range(2): | ||
logger.info("This is a test log message.") | ||
time.sleep(0.1) | ||
|
||
def test_rolling_with_size(self): | ||
logger = logging.getLogger('CustomLogger') | ||
logger.setLevel(logging.DEBUG) | ||
handler = SizeAndTimeRotatingFileHandler( | ||
filename ='test.log', | ||
when='S', | ||
interval=10, | ||
max_bytes=1*1024, | ||
backup_count=2, | ||
total_size_limit=1024*300*1024 | ||
) | ||
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') | ||
handler.setFormatter(formatter) | ||
logger.addHandler(handler) | ||
|
||
for i in range(100): | ||
logger.info("This is a test log message."*100) | ||
time.sleep(0.001) | ||
|
||
def test_rolling_to_total_max_size(self): | ||
logger = logging.getLogger('CustomLogger') | ||
logger.setLevel(logging.DEBUG) | ||
handler = SizeAndTimeRotatingFileHandler( | ||
filename ='test.log', | ||
when='S', | ||
interval=100, | ||
max_bytes=10*1024, | ||
backup_count=10000, | ||
total_size_limit=20*1024 | ||
) | ||
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') | ||
handler.setFormatter(formatter) | ||
logger.addHandler(handler) | ||
|
||
for i in range(100): | ||
logger.info("This is a test log message."*100) | ||
time.sleep(0.001) | ||
|
||
if __name__ == '__main__': | ||
unittest.main() |
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 |
---|---|---|
@@ -0,0 +1,91 @@ | ||
# Copyright (c) 2024 Baidu, Inc. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
import os | ||
import time | ||
import glob | ||
import logging | ||
from datetime import datetime, timedelta | ||
|
||
class SizeAndTimeRotatingFileHandler(logging.Handler): | ||
def __init__(self, filename, when='S', interval=1, max_bytes=0, backup_count=0, total_size_limit=0): | ||
super().__init__() | ||
self.base_filename = filename | ||
self.when = when.upper() | ||
self.interval = interval | ||
self.max_bytes = max_bytes | ||
self.backup_count = backup_count | ||
self.total_size_limit = total_size_limit | ||
self.current_time = datetime.now() | ||
self.current_file = self.base_filename | ||
self.stream = open(self.current_file, 'a') | ||
self.last_rollover = time.time() | ||
|
||
def _get_new_filename(self): | ||
suffix = self.current_time.strftime("%Y-%m-%d_%H-%M-%S") | ||
return f"{self.base_filename}.{suffix}" | ||
|
||
def emit(self, record): | ||
if self.shouldRollover(record): | ||
self.doRollover() | ||
self.stream.write(self.format(record) + '\n') | ||
self.stream.flush() | ||
|
||
def shouldRollover(self, record): | ||
current_time = time.time() | ||
current_size = os.path.getsize(self.current_file) | ||
|
||
time_rollover = False | ||
if self.when == 'S': | ||
time_rollover = current_time >= self.last_rollover + self.interval | ||
elif self.when == 'M': | ||
time_rollover = current_time >= self.last_rollover + self.interval * 60 | ||
elif self.when == 'H': | ||
time_rollover = current_time >= self.last_rollover + self.interval * 3600 | ||
elif self.when == 'D': | ||
time_rollover = current_time >= self.last_rollover + self.interval * 86400 | ||
elif self.when == 'MIDNIGHT': | ||
time_rollover = datetime.fromtimestamp(current_time).date() != datetime.fromtimestamp(self.last_rollover).date() | ||
|
||
size_rollover = current_size >= self.max_bytes if self.max_bytes > 0 else False | ||
|
||
return time_rollover or size_rollover | ||
|
||
def doRollover(self): | ||
self.stream.close() | ||
self.current_time = datetime.now() | ||
new_filename = self._get_new_filename() | ||
os.rename(self.current_file, new_filename) # Rename current file to new name | ||
self.current_file = self.base_filename | ||
self.stream = open(self.current_file, 'a') | ||
self.last_rollover = time.time() | ||
self.manage_log_files() | ||
|
||
def manage_log_files(self): | ||
log_files = sorted(glob.glob(f"{self.base_filename}.*"), key=os.path.getmtime) | ||
|
||
while len(log_files) > self.backup_count: | ||
oldest_log = log_files.pop(0) | ||
os.remove(oldest_log) | ||
|
||
while self._total_size(log_files) > self.total_size_limit: | ||
if log_files: | ||
oldest_log = log_files.pop(0) | ||
os.remove(oldest_log) | ||
|
||
def _total_size(self, files): | ||
return sum(os.path.getsize(f) for f in files if os.path.exists(f)) | ||
|
||
def close(self): | ||
self.stream.close() | ||
super().close() |
Oops, something went wrong.
Oops, something went wrong.
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.
这几个参数可以换成更通用的参数名称:
console_output
rotate_frequency
rotate_interval
max_file_size
total_log_size
max_log_files