121 lines
3.0 KiB
Dart
121 lines
3.0 KiB
Dart
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:EasyDartModule/base/logger/Logger.dart';
|
|
import 'package:dio/dio.dart';
|
|
|
|
enum LoggerLevel {
|
|
debug(1),
|
|
info(2),
|
|
warning(3),
|
|
error(4),
|
|
off(5),
|
|
;
|
|
|
|
final int level;
|
|
const LoggerLevel(this.level);
|
|
}
|
|
|
|
class LokiLogger implements Logger {
|
|
final LoggerConfig? _config;
|
|
final Dio dio;
|
|
LoggerLevel level = LoggerLevel.info;
|
|
LokiLogger(this._config)
|
|
: dio = Dio(
|
|
BaseOptions(baseUrl: _config == null ? "" : _config.host, headers: {
|
|
"Content-Type": "application/json",
|
|
if (!identical(0, 0.0)) "Content-Encoding": "gzip"
|
|
}));
|
|
@override
|
|
void debug(String msg,
|
|
{String? tag, String? traceId, String? spanId, String? parentSpanId}) {
|
|
log(msg,
|
|
level: LoggerLevel.debug,
|
|
tag: tag,
|
|
traceId: traceId,
|
|
spanId: spanId,
|
|
parentSpanId: parentSpanId);
|
|
}
|
|
|
|
@override
|
|
void info(String msg,
|
|
{String? tag, String? traceId, String? spanId, String? parentSpanId}) {
|
|
log(msg,
|
|
level: LoggerLevel.info,
|
|
tag: tag,
|
|
traceId: traceId,
|
|
spanId: spanId,
|
|
parentSpanId: parentSpanId);
|
|
}
|
|
|
|
@override
|
|
void warning(String msg,
|
|
{String? tag, String? traceId, String? spanId, String? parentSpanId}) {
|
|
log(msg,
|
|
level: LoggerLevel.warning,
|
|
tag: tag,
|
|
traceId: traceId,
|
|
spanId: spanId,
|
|
parentSpanId: parentSpanId);
|
|
}
|
|
|
|
@override
|
|
void error(String msg,
|
|
{String? tag, String? traceId, String? spanId, String? parentSpanId}) {
|
|
log(msg,
|
|
level: LoggerLevel.error,
|
|
tag: tag,
|
|
traceId: traceId,
|
|
spanId: spanId,
|
|
parentSpanId: parentSpanId);
|
|
}
|
|
|
|
void log(String msg,
|
|
{required LoggerLevel level,
|
|
String? tag,
|
|
String? traceId,
|
|
String? spanId,
|
|
String? parentSpanId}) {
|
|
if (level.level < this.level.level) {
|
|
//日志等级小于设置的输出日志等级
|
|
return;
|
|
}
|
|
String log =
|
|
"traceId=$traceId, spanId=$spanId parentSpanId=$parentSpanId tag=$tag ${level.name.toUpperCase()} $msg";
|
|
if (_config == null) {
|
|
print(log);
|
|
} else {
|
|
//推送到loki服务器
|
|
//{_config.url}
|
|
var now = DateTime.now();
|
|
// 转换为纳秒
|
|
int nanoseconds = now.microsecondsSinceEpoch * 1000;
|
|
var data = jsonEncode({
|
|
"streams": [
|
|
{
|
|
"stream": {
|
|
"service_name": _config.serviceName,
|
|
// "traceId": traceId,
|
|
// "spanId": spanId,
|
|
// "parentSpanId": parentSpanId
|
|
},
|
|
"values": [
|
|
[nanoseconds.toString(), log]
|
|
]
|
|
}
|
|
]
|
|
});
|
|
//判断平台
|
|
if (identical(0, 0.0)) {
|
|
dio.post("/loki/api/v1/push", data: data);
|
|
} else {
|
|
var zip = gzip.encode(utf8.encode(data));
|
|
dio.post("/loki/api/v1/push", data: zip);
|
|
}
|
|
if (level == LoggerLevel.debug || _config.print) {
|
|
print(log);
|
|
}
|
|
}
|
|
}
|
|
}
|