如要使用flutter官方的日志类,需要添加对该库的依赖:
dependencies:
flutter:
sdk: flutter
logger: ^1.0.0
在使用的类中,添加对logger包的引用:
import 'package:logger/logger.dart';
对logger类的简单使用:
var logger = Logger();
logger.d("debug messages!");
不同级别日志的输出:
///详细日志
logger.v("Verbose log");
///调试信息
logger.d("Debug log");
///普通信息
logger.i("Info log");
///警告信息
logger.w("Warning log");
///错误信息
logger.e("Error log");
///致命错误
logger.wtf("What a terrible failure log");
设置日志级别:
Logger.level = Level.warning;
上述设置的情况下,级别小于warning的信息将不会显示。
自定义日志级别、过滤器以及日志输出:
enum NotificationType {
info,
warn,
success,
error
}
class TbLogOutput extends LogOutput {
@override
void output(OutputEvent event) {
for (var line in event.lines) {
debugPrint(line);
}
}
}
class TbLogsFilter extends LogFilter {
@override
bool shouldLog(LogEvent event) {
if (kReleaseMode) {
return event.level.index >= Level.warning.index;
} else {
return true;
}
}
}
扩展+自定义的日志类:
class TbLogger {
final _logger = Logger(
filter: TbLogsFilter(),
printer: PrefixPrinter(
PrettyPrinter(
methodCount: 0,
errorMethodCount: 8,
lineLength: 200,
colors: false,
printEmojis: true,
printTime: false
)
),
output: TbLogOutput()
);
void verbose(dynamic message, [dynamic error, StackTrace? stackTrace]) {
_logger.v(message, error, stackTrace);
}
void debug(dynamic message, [dynamic error, StackTrace? stackTrace]) {
_logger.d(message, error, stackTrace);
}
void info(dynamic message, [dynamic error, StackTrace? stackTrace]) {
_logger.i(message, error, stackTrace);
}
void warn(dynamic message, [dynamic error, StackTrace? stackTrace]) {
_logger.w(message, error, stackTrace);
}
void error(dynamic message, [dynamic error, StackTrace? stackTrace]) {
_logger.e(message, error, stackTrace);
}
void fatal(dynamic message, [dynamic error, StackTrace? stackTrace]) {
_logger.wtf(message, error, stackTrace);
}
}
|