You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
91 lines
2.5 KiB
91 lines
2.5 KiB
import 'dart:developer' as developer;
|
|
|
|
/// 日志级别
|
|
enum LogLevel {
|
|
debug,
|
|
info,
|
|
warning,
|
|
error,
|
|
}
|
|
|
|
/// 日志工具类
|
|
///
|
|
/// 提供统一的日志记录接口,方便后续扩展和管理
|
|
class Logger {
|
|
/// 当前日志级别,低于此级别的日志不会被输出
|
|
static LogLevel _currentLevel = LogLevel.debug;
|
|
|
|
/// 设置日志级别
|
|
static void setLevel(LogLevel level) {
|
|
_currentLevel = level;
|
|
}
|
|
|
|
/// 输出调试日志
|
|
static void debug(String message, {String? tag}) {
|
|
if (_currentLevel.index <= LogLevel.debug.index) {
|
|
_log('DEBUG', message, tag: tag);
|
|
}
|
|
}
|
|
|
|
/// 输出信息日志
|
|
static void info(String message, {String? tag}) {
|
|
if (_currentLevel.index <= LogLevel.info.index) {
|
|
_log('INFO', message, tag: tag);
|
|
}
|
|
}
|
|
|
|
/// 输出警告日志
|
|
static void warning(String message, {String? tag}) {
|
|
if (_currentLevel.index <= LogLevel.warning.index) {
|
|
_log('WARNING', message, tag: tag);
|
|
}
|
|
}
|
|
|
|
/// 输出错误日志
|
|
static void error(String message, [dynamic error, StackTrace? stackTrace, String? tag]) {
|
|
if (_currentLevel.index <= LogLevel.error.index) {
|
|
_log('ERROR', message, tag: tag);
|
|
if (error != null) {
|
|
_log('ERROR', 'Original error: $error', tag: tag);
|
|
}
|
|
if (stackTrace != null) {
|
|
_log('ERROR', 'Stack trace: $stackTrace', tag: tag);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 获取当前调用栈的类名
|
|
static String? _getCallerClassName() {
|
|
try {
|
|
final stackTrace = StackTrace.current.toString();
|
|
final frames = stackTrace.split('\n');
|
|
|
|
// 查找调用者帧 (跳过Logger框架内部的帧)
|
|
for (int i = 0; i < frames.length; i++) {
|
|
final frame = frames[i].trim();
|
|
if (frame.contains('Logger.') || frame.contains('_log')) {
|
|
continue;
|
|
}
|
|
|
|
// 简单的解析类名
|
|
final regex = RegExp(r'#\d+\s+([^\.]+)\.([^\.]+)\s');
|
|
final match = regex.firstMatch(frame);
|
|
if (match != null && match.groupCount >= 1) {
|
|
return match.group(1);
|
|
}
|
|
break;
|
|
}
|
|
} catch (e) {
|
|
// 忽略解析错误
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// 内部日志输出方法
|
|
static void _log(String level, String message, {String? tag}) {
|
|
final timestamp = DateTime.now().toString();
|
|
final className = tag ?? _getCallerClassName() ?? '';
|
|
final tagInfo = className.isNotEmpty ? '[$className] ' : '';
|
|
developer.log('[$timestamp][$level][$tagInfo]: $message');
|
|
}
|
|
}
|
|
|