首次提交

This commit is contained in:
qmqz
2025-01-02 10:08:03 +08:00
commit fd62ed3d98
16 changed files with 1143 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
abstract class Logger {
static late Logger _logger;
static Logger getInstance() {
return _logger;
}
static void setInstance(Logger logger) {
_logger = logger;
}
void info(String msg, {String tag});
void warning(String msg, {String tag});
void error(String msg, {String tag});
}
class LoggerConfig {
String host;
String serviceName;
LoggerConfig({required this.host, required this.serviceName});
}

View File

@@ -0,0 +1,72 @@
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",
"Content-Encoding": "gzip"
}));
@override
void info(String msg, {String? tag}) {
log(msg, level: LoggerLevel.info, tag: tag);
}
@override
void warning(String msg, {String? tag}) {
log(msg, level: LoggerLevel.warning, tag: tag);
}
@override
void error(String msg, {String? tag}) {
log(msg, level: LoggerLevel.error, tag: tag);
}
void log(String msg, {required LoggerLevel level, String? tag}) {
if (level.level < this.level.level) {
//日志等级小于设置的输出日志等级
return;
}
if (_config == null) {
print("$tag $level $msg");
} else {
//推送到loki服务器
//{_config.url}
var now = DateTime.now();
// 转换为纳秒
int nanoseconds = now.microsecondsSinceEpoch * 1000;
var zip = gzip.encode(utf8.encode(jsonEncode({
"streams": [
{
"stream": {"service_name": _config.serviceName},
"values": [
[nanoseconds.toString(), "$tag ${level.name.toUpperCase()} $msg"]
]
}
]
})));
dio.post("/loki/api/v1/push", data: zip);
}
}
}