# EasyElasticLogger
**Repository Path**: lovelydouble/easy-elastic-logger
## Basic Information
- **Project Name**: EasyElasticLogger
- **Description**: 一个轻量级、易于使用的.NET日志库,专门用于将结构化日志写入Elasticsearch。支持多种.NET平台,包括.NET Framework和.NET Core/.NET 5+
- **Primary Language**: C#
- **License**: MIT
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2025-11-25
- **Last Updated**: 2025-12-07
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# EasyElasticLogger
> 🚀🚀🚀 一个轻量级、易于使用的.NET日志库,专门用于将结构化日志写入Elasticsearch。支持多种.NET平台,包括.NET Framework和.NET Core/.NET 5+
**简单易用 | 功能丰富 | 生产就绪**
## 功能特性
| 特性类别 | 功能描述 |
|----------|----------|
| ✅ **多平台支持** | 兼容 .NET Framework 4.7.2+, .NET Framework 4.8, .NET Standard 2.0, .NET Standard 2.1 |
| ✅ **结构化日志** | 将日志以结构化格式写入Elasticsearch,便于查询和分析 |
| ✅ **高性能** | 内置日志缓冲机制,批量发送日志以提高性能 |
| ✅ **灵活配置** | 支持多种配置方式,包括代码配置和JSON文件配置 |
| ✅ **丰富日志级别** | 支持 Debug, Info, Warn, Error, Fatal 五种日志级别 |
| ✅ **安全连接** | 支持HTTPS和基本身份验证 |
| ✅ **索引管理** | 支持固定索引和按日期滚动索引策略 |
---
## 适用场景
### 需要将日志集中到 ELK 进行统一分析的系统
- 需要实时日志监控和告警的系统
- 希望利用 Kibana 进行日志可视化和分析的场景
### 基于 .NET Framework 的应用程序
- **WinForm** 桌面应用程序(.NET Framework 4.7.2/4.8)
- **WPF** 桌面应用程序(.NET Framework 4.7.2/4.8)
- **WebForm** 传统 Web 应用程序(.NET Framework 4.7.2/4.8)
- **Windows服务** 和后台任务程序(.NET Framework 4.7.2/4.8)
- **控制台应用程序** 的日志记录需求(.NET Framework 4.7.2/4.8)
### 基于 .NET Core/.NET 5+ 的应用程序
- ASP.NET Core Web API 应用程序
- .NET Core 控制台应用程序
- 跨平台应用程序(Windows/Linux/macOS)
### 特殊开发环境中的诊断与运维日志需求
- AutoCAD 二次开发插件的日志记录(基于.NET Framework)
- Revit 等BIM软件的插件开发(基于.NET Framework)
- 工业软件插件的诊断和运维监控
---
## 兼容性说明
| Log Library Version | Compatible with Elasticsearch 8.x | Compatible with Elasticsearch 9.x | Compatible with Elasticsearch 10.x |
|---------------------|-----------------------------------|-----------------------------------|------------------------------------|
| 9.x | ❌ no | ✅ yes | ✅ yes |
| 8.x | ✅ yes | ✅ yes | ❌ no |
---
## 安装
通过NuGet包管理器安装:
```bash
Install-Package EasyElasticLogger
```
或者通过.NET CLI:
```bash
dotnet add package EasyElasticLogger
```
---
## 🚀🚀🚀 快速开始
### 1. 基本使用
```csharp
using EasyElasticLogger.ES.Logging;
// 在应用程序启动时初始化(如Program.cs或Startup.cs中)
// 创建配置
var config = new LoggerConfiguration
{
Enabled = true,
IndexPrefix = "demo-app-log",
ApplicationName = "DemoApplication",
Cluster = new ClusterConfiguration
{
Nodes = new List { "http://localhost:9200" }
// 注意:在实际使用中,您需要提供有效的Elasticsearch连接信息
}
};
// 初始化静态日志记录器
ElasticLogger.Initialize(config);
// 在任何需要记录日志的地方直接使用静态方法
// 同步记录日志
ElasticLogger.Info("这是一条信息日志");
ElasticLogger.Warn("这是一条警告日志");
ElasticLogger.Error("这是一条错误日志", new Exception("测试异常"));
// 异步记录日志
await ElasticLogger.InfoAsync("这是一条异步信息日志");
await ElasticLogger.ErrorAsync("这是一条异步错误日志", new Exception("测试异常"));
```
---
## ⚙⚙⚙ 配置方式
配置加载优先级:**直接传参 > JSON配置**
### 1. 直接传参配置
```csharp
var config = new LoggerConfiguration
{
Enabled = true,
IndexPrefix = "myapp-log",
IndexStrategy = IndexStrategy.DailyRolling,
ApplicationName = "MyApplication",
BatchSize = 100,
TimeoutMs = 10000,
Cluster = new ClusterConfiguration
{
Nodes = new List { "http://localhost:9200" },
Username = "elastic",
Password = "password",
UseSsl = false,
SkipSslVerification = false,
ConnectionTimeoutMs = 5000,
MaxRetries = 2
}
};
ElasticLogger.Initialize(config);
```
### 2. JSON配置文件(支持环境特定配置)
```csharp
// 会自动查找 logger-config.Production.json 或 logger-config.json
ElasticLogger.InitializeFromJson("logger-config.json", "Production");
```
#### JSON配置文件示例
**默认配置 (logger-config.json)**
```json
{
"Enabled": true,
"IndexPrefix": "myapp-log",
"IndexStrategy": "DailyRolling",
"ApplicationName": "MyApplication",
"BatchSize": 100,
"TimeoutMs": 10000,
"Cluster": {
"Nodes": ["http://localhost:9200"],
"Username": "elastic",
"Password": "password",
"UseSsl": false,
"SkipSslVerification": false,
"ConnectionTimeoutMs": 5000,
"MaxRetries": 2
}
}
```
**生产环境配置 (logger-config.Production.json)**
```json
{
"Enabled": true,
"IndexPrefix": "myapp-log-prod",
"IndexStrategy": "DailyRolling",
"ApplicationName": "MyProductionApp",
"BatchSize": 100,
"TimeoutMs": 10000,
"Cluster": {
"Nodes": ["http://prod-es1:9200", "http://prod-es2:9200", "http://prod-es3:9200"],
"Username": "elastic",
"Password": "prod_password",
"UseSsl": true,
"SkipSslVerification": false,
"ConnectionTimeoutMs": 10000,
"MaxRetries": 3
}
}
```
**使用示例**
```csharp
// 使用默认JSON配置文件
ElasticLogger.InitializeFromJson("logger-config.json");
// 使用指定环境的JSON配置文件
ElasticLogger.InitializeFromJson("logger-config.json", "Production");
```
### 3. 自定义配置文件路径
```csharp
// 使用自定义配置文件路径和环境初始化
ElasticLogger.InitializeFromJson(@"C:\MyApp\config\logger-config.json", "Production");
```
---
## 日志记录示例
### 同步日志记录
```csharp
// Debug级别日志
ElasticLogger.Debug("调试信息", "MyClass.Method");
// Info级别日志
ElasticLogger.Info("一般信息", "MyClass.Method");
// Warn级别日志
ElasticLogger.Warn("警告信息", "MyClass.Method");
// Error级别日志
ElasticLogger.Error("错误信息", new Exception("异常详情"), "MyClass.Method");
// Fatal级别日志
ElasticLogger.Fatal("严重错误", new Exception("异常详情"), "MyClass.Method");
// 带附加数据的日志
var userData = new { UserId = 123, UserName = "张三" };
ElasticLogger.Info("用户登录", "UserService.Login", userData);
```
### 异步日志记录
```csharp
// 异步记录不同级别的日志
await ElasticLogger.DebugAsync("调试信息", "MyClass.Method");
await ElasticLogger.InfoAsync("一般信息", "MyClass.Method");
await ElasticLogger.WarnAsync("警告信息", "MyClass.Method");
await ElasticLogger.ErrorAsync("错误信息", new Exception("异常详情"), "MyClass.Method");
await ElasticLogger.FatalAsync("严重错误", new Exception("异常详情"), "MyClass.Method");
```
---
## 配置参数详解
### Logger配置项
| 属性 | 类型 | 默认值 | 描述 |
|------|------|--------|------|
| `Enabled` | `bool` | `true` | 是否启用日志记录功能 |
| `IndexPrefix` | `string` | `"app-log"` | 索引前缀 |
| `IndexStrategy` | `IndexStrategy` | `DailyRolling` | 索引策略(Fixed/DailyRolling) |
| `FixedIndexName` | `string` | `null` | 固定索引名称(仅在IndexStrategy为Fixed时使用) |
| `ApplicationName` | `string` | `"DefaultApp"` | 应用程序名称 |
| `BatchSize` | `int` | `100` | 批量发送日志的大小 |
| `TimeoutMs` | `int` | `10000` | 发送超时时间(毫秒) |
### Cluster配置项
| 属性 | 类型 | 默认值 | 描述 |
|------|------|--------|------|
| `Nodes` | `List` | `empty` | Elasticsearch节点地址列表 |
| `Username` | `string` | `null` | 用户名(用于Basic认证) |
| `Password` | `string` | `null` | 密码(用于Basic认证) |
| `UseSsl` | `bool` | `false` | 是否启用SSL |
| `SkipSslVerification` | `bool` | `false` | 是否跳过SSL证书验证 |
| `ConnectionTimeoutMs` | `int` | `5000` | 连接超时时间(毫秒) |
| `MaxRetries` | `int` | `2` | 最大重试次数 |
### IndexStrategy索引策略
| 策略 | 描述 |
|------|------|
| **Fixed** | 固定索引,所有日志都写入同一个索引 |
| **DailyRolling** | 按日期滚动索引,每天生成一个新的索引(默认) |
---
## 许可证
本项目采用 **MIT许可证** - 查看 LICENSE 文件了解详情。
---
## 不同环境下的配置和使用示例
### .NET Framework/.NET Core/.NET 5+ 环境配置和使用
#### 1. Program.cs 中的初始化和使用
```csharp
using EasyElasticLogger.ES.Configuration;
using EasyElasticLogger.ES.Logging;
using System;
using System.Collections.Generic;
namespace MyNetFrameworkApp
{
class Program
{
static void Main(string[] args)
{
// 初始化日志记录器
InitializeLogger();
// 记录不同级别的日志
ElasticLogger.Info("应用程序启动", "Program.Main");
try
{
// 模拟业务逻辑
DoWork();
}
catch (Exception ex)
{
ElasticLogger.Error("应用程序发生未处理异常", ex, "Program.Main");
}
ElasticLogger.Info("应用程序结束", "Program.Main");
Console.WriteLine("按任意键退出...");
Console.ReadKey();
}
static void InitializeLogger()
{
var config = new LoggerConfiguration
{
Enabled = true,
IndexPrefix = "myapp-log",
ApplicationName = "MyNetFrameworkApp",
Cluster = new ClusterConfiguration
{
Nodes = new List { "http://localhost:9200" },
Username = "elastic",
Password = "your_password"
}
};
ElasticLogger.Initialize(config);
Console.WriteLine("日志记录器初始化完成");
}
static void DoWork()
{
ElasticLogger.Info("开始执行业务逻辑", "Program.DoWork");
// 模拟一些工作
System.Threading.Thread.Sleep(1000);
// 记录带附加数据的日志
var userData = new { UserId = 1001, UserName = "张三", Action = "查询数据" };
ElasticLogger.Info("用户执行操作", "UserService.QueryData", userData);
ElasticLogger.Info("业务逻辑执行完成", "Program.DoWork");
}
}
}
```
### ASP.NET Core Web API 环境配置和使用
#### 1. appsettings.json 配置示例
```json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ElasticLogger": {
"Enabled": true,
"IndexPrefix": "webapi-log",
"ApplicationName": "MyWebApiApp",
"Cluster": {
"Nodes": [ "http://localhost:9200" ],
"Username": "elastic",
"Password": "your_password",
"UseSsl": false,
"SkipSslVerification": false
}
},
"AllowedHosts": "*"
}
```
#### 2. Program.cs 中的初始化和使用
```csharp
using EasyElasticLogger.ES.Configuration;
using EasyElasticLogger.ES.Logging;
var builder = WebApplication.CreateBuilder(args);
// 添加控制器服务
builder.Services.AddControllers();
// 从配置文件初始化ElasticLogger
var elasticLoggerConfig = new LoggerConfiguration
{
Enabled = builder.Configuration.GetValue("ElasticLogger:Enabled"),
IndexPrefix = builder.Configuration.GetValue("ElasticLogger:IndexPrefix") ?? "webapi-log",
ApplicationName = builder.Configuration.GetValue("ElasticLogger:ApplicationName") ?? "MyWebApiApp",
Cluster = new ClusterConfiguration
{
Nodes = builder.Configuration.GetSection("ElasticLogger:Cluster:Nodes").Get>() ?? new List { "http://localhost:9200" },
Username = builder.Configuration.GetValue("ElasticLogger:Cluster:Username"),
Password = builder.Configuration.GetValue("ElasticLogger:Cluster:Password"),
UseSsl = builder.Configuration.GetValue("ElasticLogger:Cluster:UseSsl"),
SkipSslVerification = builder.Configuration.GetValue("ElasticLogger:Cluster:SkipSslVerification")
}
};
ElasticLogger.Initialize(elasticLoggerConfig);
// 记录应用程序启动日志
ElasticLogger.Info("Web API 应用程序正在启动");
var app = builder.Build();
// 配置HTTP请求管道
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthorization();
app.MapControllers();
// 应用程序启动完成后的日志
app.Lifetime.ApplicationStarted.Register(() =>
{
ElasticLogger.Info("Web API 应用程序已成功启动");
});
app.Run();
```
#### 3. 控制器中使用日志记录
```csharp
using Microsoft.AspNetCore.Mvc;
using EasyElasticLogger.ES.Logging;
namespace MyWebApiApp.Controllers
{
[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
try
{
ElasticLogger.Info($"开始查询用户信息,用户ID: {id}", "UserController.GetUser");
// 模拟数据库查询
var user = new { Id = id, Name = "张三", Email = "zhangsan@example.com" };
// 记录带附加数据的日志
ElasticLogger.Info("用户信息查询成功", "UserController.GetUser", user);
return Ok(user);
}
catch (Exception ex)
{
ElasticLogger.Error($"查询用户信息失败,用户ID: {id}", ex, "UserController.GetUser");
return StatusCode(500, "内部服务器错误");
}
}
[HttpPost]
public async Task CreateUser([FromBody] CreateUserRequest request)
{
try
{
ElasticLogger.Info("开始创建用户", "UserController.CreateUser", request);
// 模拟异步数据库操作
await Task.Delay(100);
// 记录异步日志
await ElasticLogger.InfoAsync("用户创建成功", "UserController.CreateUser", request);
return Ok(new { Message = "用户创建成功" });
}
catch (Exception ex)
{
await ElasticLogger.ErrorAsync("创建用户失败", ex, "UserController.CreateUser", request);
return StatusCode(500, "内部服务器错误");
}
}
}
public class CreateUserRequest
{
public string Name { get; set; }
public string Email { get; set; }
}
}
```
**让日志记录变得简单而强大** ✨✨✨