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); } } }