inklog 0.1.0

Enterprise-grade Rust logging infrastructure
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
# Inklog API 参考文档

本文档提供 Inklog 公共 API 的完整参考。

---

## 目录

- [概述]#概述
- [核心类型]#核心类型
  - [LoggerManager]#loggermanager
  - [LoggerBuilder]#loggerbuilder
  - [InklogConfig]#inklogconfig
- [配置结构体]#配置结构体
  - [GlobalConfig]#globalconfig
  - [ConsoleSinkConfig]#consolesinkconfig
  - [FileSinkConfig]#filesinkconfig
  - [DatabaseSinkConfig]#databasesinkconfig
  - [S3ArchiveConfig]#s3archiveconfig
  - [HttpServerConfig]#httpserverconfig
  - [PerformanceConfig]#performanceconfig
  - [ParquetConfig]#parquetconfig
- [错误类型]#错误类型
- [健康监控类型]#健康监控类型
- [特征(Traits)]#特征traits

---

## 概述

Inklog 提供了以下公共 API 类型:

| 类型 | 模块 | 描述 |
|------|--------|------|
| `LoggerManager` | `manager` | 核心日志管理器,协调所有日志操作 |
| `LoggerBuilder` | `manager` | 流式构建器,用于创建配置 |
| `InklogConfig` | `config` | 根配置结构 |
| `InklogError` | `error` | 错误类型枚举 |
| `HealthStatus` | `metrics` | 健康状态结构 |
| `Metrics` | `metrics` | 指标收集器 |

### 导入公共 API

```rust
use inklog::{
    // 核心类型
    LoggerManager,
    LoggerBuilder,
    InklogConfig,

    // 配置类型
    config::{
        GlobalConfig,
        ConsoleSinkConfig,
        FileSinkConfig,
        DatabaseSinkConfig,
        HttpServerConfig,
        PerformanceConfig,
        ParquetConfig,
        DatabaseDriver,
    },

    // 错误类型
    InklogError,

    // 健康监控
    HealthStatus,
    Metrics,
};
```

---

## 核心类型

### LoggerManager

核心日志管理器,协调日志收集和路由到各个 Sink。

#### 定义

```rust
pub struct LoggerManager {
    // 内部字段
}
```

#### 方法

##### `new`

创建带有默认配置的新 `LoggerManager`。

**签名**
```rust
pub async fn new() -> Result<Self, InklogError>
```

**返回值**
- `Ok(LoggerManager)` - 成功创建的管理器
- `Err(InklogError)` - 初始化失败

**示例**
```rust
use inklog::LoggerManager;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let _logger = LoggerManager::new().await?;
    Ok(())
}
```

---

##### `with_config`

使用给定配置创建新的 `LoggerManager`。

**签名**
```rust
pub async fn with_config(config: InklogConfig) -> Result<Self, InklogError>
```

**参数**
- `config` - 日志系统配置

**返回值**
- `Ok(LoggerManager)` - 成功创建的管理器
- `Err(InklogError)` - 初始化失败

**示例**
```rust
use inklog::{FileSinkConfig, InklogConfig, LoggerManager};

let config = InklogConfig {
    file_sink: Some(FileSinkConfig {
        enabled: true,
        path: "logs/app.log".into(),
        ..Default::default()
    }),
    ..Default::default()
};

let _logger = LoggerManager::with_config(config).await?;
```

---

##### `get_health_status`

获取当前健康状态。

**签名**
```rust
pub fn get_health_status(&self) -> HealthStatus
```

**返回值**
- `HealthStatus` - 包含系统健康信息的结构

**示例**
```rust
let health = logger.get_health_status();
println!("整体状态: {:?}", health.overall_status);
println!("Sink 状态: {:?}", health.sinks);
```

---

##### `recover_sink`

手动恢复特定的 Sink。

**签名**
```rust
pub fn recover_sink(&self, sink_name: &str) -> Result<(), InklogError>
```

**参数**
- `sink_name` - 要恢复的 Sink 名称(如:`"file"``"database"`
**返回值**
- `Ok(())` - 恢复命令已发送
- `Err(InklogError)` - 发送恢复命令失败

**示例**
```rust
// 恢复文件 Sink
logger.recover_sink("file")?;

// 恢复数据库 Sink
logger.recover_sink("database")?;
```

---

##### `trigger_recovery_for_unhealthy_sinks`

触发所有不健康 Sink 的恢复。

**签名**
```rust
pub fn trigger_recovery_for_unhealthy_sinks(&self) -> Result<Vec<String>, InklogError>
```

**返回值**
- `Ok(Vec<String>)` - 已恢复的 Sink 名称列表
- `Err(InklogError)` - 恢复操作失败

**示例**
```rust
let recovered = logger.trigger_recovery_for_unhealthy_sinks()?;
for sink in &recovered {
    println!("已恢复: {}", sink);
}
```

---

##### `shutdown`

优雅关闭日志系统。

**签名**
```rust
pub fn shutdown(&self) -> Result<(), InklogError>
```

**返回值**
- `Ok(())` - 关闭成功
- `Err(InklogError)` - 关闭失败

**示例**
```rust
logger.shutdown()?;
```

---

##### `start_archive_service`

启动 S3 归档服务(需要 `aws` 功能)。

**签名**
```rust
#[cfg(feature = "aws")]
pub async fn start_archive_service(&self) -> Result<(), InklogError>
```

**返回值**
- `Ok(())` - 归档服务已启动
- `Err(InklogError)` - 启动失败

**示例**
```rust
#[cfg(feature = "aws")]
{
    logger.start_archive_service().await?;
}
```

---

##### `stop_archive_service`

停止 S3 归档服务(需要 `aws` 功能)。

**签名**
```rust
#[cfg(feature = "aws")]
pub async fn stop_archive_service(&self) -> Result<(), InklogError>
```

**返回值**
- `Ok(())` - 归档服务已停止
- `Err(InklogError)` - 停止失败

**示例**
```rust
#[cfg(feature = "aws")]
{
    logger.stop_archive_service().await?;
}
```

---

##### `trigger_archive`

手动触发归档操作(需要 `aws` 功能)。

**签名**
```rust
#[cfg(feature = "aws")]
pub async fn trigger_archive(&self) -> Result<String, InklogError>
```

**返回值**
- `Ok(String)` - 归档对象的键
- `Err(InklogError)` - 归档失败

**示例**
```rust
#[cfg(feature = "aws")]
{
    match logger.trigger_archive().await {
        Ok(archive_key) => println!("归档完成: {}", archive_key),
        Err(e) => println!("归档失败: {}", e),
    }
}
```

---

##### `build_detached`

构建 LoggerManager 但不安装全局订阅者。这主要用于测试和基准测试。

**签名**
```rust
pub async fn build_detached(
    config: InklogConfig,
) -> Result<(LoggerManager, LoggerSubscriber, tracing_subscriber::EnvFilter), InklogError>
```

**返回值**
- `Ok((LoggerManager, LoggerSubscriber, EnvFilter))` - 构建的管理器、订阅者和过滤器
- `Err(InklogError)` - 构建失败

**示例**
```rust
use inklog::{InklogConfig, LoggerManager};

let config = InklogConfig::default();
let (manager, subscriber, filter) = LoggerManager::build_detached(config).await?;
// 可以手动设置订阅者
```

---

##### `with_watch`

使用配置文件监视器创建 LoggerManager(需要 `confers` 功能)。

**签名**
```rust
#[cfg(feature = "confers")]
pub async fn with_watch() -> Result<Self, InklogError>
```

**返回值**
- `Ok(LoggerManager)` - 管理器实例,配置变更会自动重新加载
- `Err(InklogError)` - 初始化失败

**示例**
```rust
#[cfg(feature = "confers")]
{
    let logger = LoggerManager::with_watch().await?;
    // 配置文件变更时会自动重新加载
}
```

---

##### `from_file`

从指定路径加载配置文件(需要 `confers` 功能)。

**签名**
```rust
#[cfg(feature = "confers")]
pub fn from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self, InklogError>
```

**参数**
- `path` - 配置文件路径

**返回值**
- `Ok(InklogConfig)` - 加载的配置
- `Err(InklogError)` - 加载失败

**示例**
```rust
#[cfg(feature = "confers")]
{
    let config = InklogConfig::from_file("inklog_config.toml")?;
    let logger = LoggerManager::with_config(config).await?;
}
```

---

##### `load`

从默认位置加载配置文件(需要 `confers` 功能)。

**签名**
```rust
#[cfg(feature = "confers")]
pub fn load() -> Result<Self, InklogError>
```

**返回值**
- `Ok(InklogConfig)` - 加载的配置
- `Err(InklogError)` - 加载失败

**默认查找位置**
- `/etc/inklog/config.toml`
- `./inklog_config.toml`
- `./config/inklog.toml`

**示例**
```rust
#[cfg(feature = "confers")]
{
    let config = InklogConfig::load()?;
    let logger = LoggerManager::with_config(config).await?;
}
```

---

### LoggerBuilder

流式构建器,用于创建 `LoggerManager` 配置。

#### 定义

```rust
pub struct LoggerBuilder {
    config: InklogConfig,
}
```

#### 方法

##### `new`

创建新的 `LoggerBuilder`。

**签名**
```rust
pub fn new() -> Self
```

**示例**
```rust
use inklog::LoggerBuilder;

let builder = LoggerBuilder::new();
```

---

##### `level`

设置全局日志级别。

**签名**
```rust
pub fn level(mut self, level: impl Into<String>) -> Self
```

**参数**
- `level` - 日志级别(`"trace"``"debug"``"info"``"warn"``"error"`
**返回值**
- `Self` - 构建器链

**示例**
```rust
let builder = LoggerBuilder::new()
    .level("debug");
```

---

##### `format`

设置日志格式字符串。

**签名**
```rust
pub fn format(mut self, format: impl Into<String>) -> Self
```

**参数**
- `format` - 格式字符串

**返回值**
- `Self` - 构建器链

**示例**
```rust
let builder = LoggerBuilder::new()
    .format("[{timestamp}] {level}: {message}");
```

---

##### `console`

启用或禁用控制台 Sink。

**签名**
```rust
pub fn console(mut self, enabled: bool) -> Self
```

**参数**
- `enabled` - 是否启用控制台 Sink

**返回值**
- `Self` - 构建器链

**示例**
```rust
let builder = LoggerBuilder::new()
    .console(true);
```

---

##### `file`

配置文件 Sink。

**签名**
```rust
pub fn file(mut self, path: impl Into<std::path::PathBuf>) -> Self
```

**参数**
- `path` - 日志文件路径

**返回值**
- `Self` - 构建器链

**示例**
```rust
let builder = LoggerBuilder::new()
    .file("logs/app.log");
```

---

##### `database`

配置数据库 Sink。

**签名**
```rust
pub fn database(mut self, url: impl Into<String>) -> Self
```

**参数**
- `url` - 数据库连接 URL

**返回值**
- `Self` - 构建器链

**示例**
```rust
let builder = LoggerBuilder::new()
    .database("sqlite://logs/app.db");
```

---

##### `s3_archive`

配置 S3 归档(需要 `aws` 功能)。

**签名**
```rust
#[cfg(feature = "aws")]
pub fn s3_archive(mut self, bucket: impl Into<String>, region: impl Into<String>) -> Self
```

**参数**
- `bucket` - S3 存储桶名称
- `region` - AWS 区域

**返回值**
- `Self` - 构建器链

**示例**
```rust
#[cfg(feature = "aws")]
{
    let builder = LoggerBuilder::new()
        .s3_archive("my-bucket", "us-west-2");
}
```

---

##### `channel_capacity`

设置日志通道容量。

**签名**
```rust
pub fn channel_capacity(mut self, capacity: usize) -> Self
```

**参数**
- `capacity` - 通道容量

**返回值**
- `Self` - 构建器链

**示例**
```rust
let builder = LoggerBuilder::new()
    .channel_capacity(20000);
```

---

##### `worker_threads`

设置工作线程数。

**签名**
```rust
pub fn worker_threads(mut self, threads: usize) -> Self
```

**参数**
- `threads` - 工作线程数

**返回值**
- `Self` - 构建器链

**示例**
```rust
let builder = LoggerBuilder::new()
    .worker_threads(4);
```

---

##### `http_server`

配置 HTTP 服务器。

**签名**
```rust
pub fn http_server(mut self, host: impl Into<String>, port: u16) -> Self
```

**参数**
- `host` - 监听主机地址
- `port` - 监听端口

**返回值**
- `Self` - 构建器链

**示例**
```rust
let builder = LoggerBuilder::new()
    .http_server("0.0.0.0", 8080);
```

---

##### `build`

构建并返回 `LoggerManager`。

**签名**
```rust
pub async fn build(self) -> Result<LoggerManager, InklogError>
```

**返回值**
- `Ok(LoggerManager)` - 成功构建的管理器
- `Err(InklogError)` - 构建失败

**示例**
```rust
use inklog::LoggerBuilder;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let logger = LoggerBuilder::new()
        .level("debug")
        .file("logs/app.log")
        .database("sqlite://logs/app.db")
        .channel_capacity(20000)
        .worker_threads(4)
        .build()
        .await?;

    Ok(())
}
```

---

### InklogConfig

根配置结构,包含所有子配置。

#### 定义

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct InklogConfig {
    pub global: GlobalConfig,
    pub console_sink: Option<ConsoleSinkConfig>,
    pub file_sink: Option<FileSinkConfig>,
    pub database_sink: Option<DatabaseSinkConfig>,
    pub s3_archive: Option<crate::archive::S3ArchiveConfig>,
    pub performance: PerformanceConfig,
    pub http_server: Option<HttpServerConfig>,
}
```

#### 字段说明

| 字段 | 类型 | 默认值 | 描述 |
|------|------|----------|------|
| `global` | `GlobalConfig` | `default()` | 全局配置 |
| `console_sink` | `Option<ConsoleSinkConfig>` | `Some(default())` | 控制台 Sink 配置 |
| `file_sink` | `Option<FileSinkConfig>` | `None` | 文件 Sink 配置 |
| `database_sink` | `Option<DatabaseSinkConfig>` | `None` | 数据库 Sink 配置(包含 ParquetConfig) |
| `s3_archive` | `Option<S3ArchiveConfig>` | `None` | S3 归档配置(包含 ParquetConfig) |
| `performance` | `PerformanceConfig` | `default()` | 性能配置 |
| `http_server` | `Option<HttpServerConfig>` | `None` | HTTP 服务器配置 |

**注意**: `ParquetConfig` 不是 `InklogConfig` 的直接字段,而是 `DatabaseSinkConfig` 和 `S3ArchiveConfig` 的内部字段。

#### 方法

##### `validate`

验证配置是否有效。

**签名**
```rust
pub fn validate(&self) -> Result<(), InklogError>
```

**返回值**
- `Ok(())` - 配置有效
- `Err(InklogError)` - 配置无效

**示例**
```rust
let config = InklogConfig::default();
config.validate()?;
```

---

##### `apply_env_overrides`

应用环境变量覆盖配置。

**签名**
```rust
pub fn apply_env_overrides(&mut self)
```

**示例**
```rust
let mut config = InklogConfig::default();
config.apply_env_overrides();
```

---

## 配置结构体

### GlobalConfig

全局配置,应用于所有日志输出。

#### 定义

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GlobalConfig {
    pub level: String,
    pub format: String,
    pub masking_enabled: bool,
}
```

#### 字段说明

| 字段 | 类型 | 默认值 | 描述 |
|------|------|----------|------|
| `level` | `String` | `"info"` | 日志级别:`trace``debug``info``warn``error` |
| `format` | `String` | `"{timestamp} [{level}] {target} - {message}"` | 日志格式模板 |
| `masking_enabled` | `bool` | `true` | 是否启用数据脱敏 |

#### 格式变量

| 变量 | 描述 |
|--------|------|
| `{timestamp}` | ISO 8601 格式的时间戳 |
| `{level}` | 日志级别(TRACE/DEBUG/INFO/WARN/ERROR) |
| `{target}` | 日志目标(模块/文件名) |
| `{message}` | 日志消息内容 |
| `{file}` | 源代码文件名 |
| `{line}` | 源代码行号 |
| `{thread_id}` | 线程标识符 |

**示例**
```rust
use inklog::config::GlobalConfig;

let global = GlobalConfig {
    level: "debug".to_string(),
    format: "[{timestamp}] [{level}] {target} - {message}".to_string(),
    masking_enabled: true,
};
```

---

### ConsoleSinkConfig

控制台 Sink 配置。

#### 定义

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ConsoleSinkConfig {
    pub enabled: bool,
    pub colored: bool,
    pub stderr_levels: Vec<String>,
}
```

#### 字段说明

| 字段 | 类型 | 默认值 | 描述 |
|------|------|----------|------|
| `enabled` | `bool` | `true` | 是否启用控制台 Sink |
| `colored` | `bool` | `true` | 是否使用彩色输出 |
| `stderr_levels` | `Vec<String>` | `["error", "warn"]` | 输出到 stderr 的日志级别 |

**示例**
```rust
use inklog::config::ConsoleSinkConfig;

let console = ConsoleSinkConfig {
    enabled: true,
    colored: true,
    stderr_levels: vec!["error".to_string(), "warn".to_string()],
};
```

---

### FileSinkConfig

文件 Sink 配置,支持轮转、压缩和加密。

#### 定义

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileSinkConfig {
    pub enabled: bool,
    pub path: PathBuf,
    pub max_size: String,
    pub rotation_time: String,
    pub keep_files: u32,
    pub compress: bool,
    pub compression_level: i32,
    pub encrypt: bool,
    pub encryption_key_env: Option<String>,
    pub retention_days: u32,
    pub max_total_size: String,
    pub cleanup_interval_minutes: u64,
}
```

#### 字段说明

| 字段 | 类型 | 默认值 | 描述 |
|------|------|----------|------|
| `enabled` | `bool` | `true` | 是否启用文件 Sink |
| `path` | `PathBuf` | `"logs/app.log"` | 日志文件路径 |
| `max_size` | `String` | `"100MB"` | 触发轮转的最大文件大小 |
| `rotation_time` | `String` | `"daily"` | 时间轮转策略:`hourly``daily``weekly` |
| `keep_files` | `u32` | `30` | 保留的轮转文件数量 |
| `compress` | `bool` | `true` | 是否压缩轮转文件 |
| `compression_level` | `i32` | `3` | 压缩级别(0-22) |
| `encrypt` | `bool` | `false` | 是否加密日志文件 |
| `encryption_key_env` | `Option<String>` | `None` | 加密密钥的环境变量名 |
| `retention_days` | `u32` | `30` | 日志保留天数 |
| `max_total_size` | `String` | `"1GB"` | 日志目录最大总大小 |
| `cleanup_interval_minutes` | `u64` | `60` | 清理旧日志的间隔(分钟) |

**示例**
```rust
use inklog::config::FileSinkConfig;
use std::path::PathBuf;

let file_config = FileSinkConfig {
    enabled: true,
    path: PathBuf::from("logs/app.log"),
    max_size: "50MB".to_string(),
    rotation_time: "daily".to_string(),
    keep_files: 14,
    compress: true,
    compression_level: 5,
    encrypt: false,
    encryption_key_env: None,
    retention_days: 30,
    max_total_size: "2GB".to_string(),
    cleanup_interval_minutes: 60,
};
```

---

### DatabaseSinkConfig

数据库 Sink 配置。

#### 定义

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseSinkConfig {
    pub enabled: bool,
    pub driver: DatabaseDriver,
    pub url: String,
    pub pool_size: u32,
    pub batch_size: usize,
    pub flush_interval_ms: u64,
    pub archive_to_s3: bool,
    pub archive_after_days: u32,
    pub s3_bucket: Option<String>,
    pub s3_region: Option<String>,
    pub table_name: String,
    pub archive_format: String,
    pub parquet_config: ParquetConfig,
}
```

#### 字段说明

| 字段 | 类型 | 默认值 | 描述 |
|------|------|----------|------|
| `enabled` | `bool` | `false` | 是否启用数据库 Sink |
| `driver` | `DatabaseDriver` | `PostgreSQL` | 数据库驱动 |
| `url` | `String` | `"postgres://localhost/logs"` | 数据库连接 URL |
| `pool_size` | `u32` | `10` | 连接池大小 |
| `batch_size` | `usize` | `100` | 批量写入的日志数量 |
| `flush_interval_ms` | `u64` | `500` | 刷新间隔(毫秒) |
| `archive_to_s3` | `bool` | `false` | 是否归档到 S3 |
| `archive_after_days` | `u32` | `30` | 归档前的保留天数 |
| `s3_bucket` | `Option<String>` | `None` | S3 存储桶名称 |
| `s3_region` | `Option<String>` | `Some("us-east-1")` | S3 区域 |
| `table_name` | `String` | `"logs"` | 日志表名 |
| `archive_format` | `String` | `"json"` | 归档格式:`json``parquet` |
| `parquet_config` | `ParquetConfig` | `default()` | Parquet 导出配置 |

**示例**
```rust
use inklog::config::{DatabaseSinkConfig, DatabaseDriver};

let db_config = DatabaseSinkConfig {
    enabled: true,
    driver: DatabaseDriver::SQLite,
    url: "sqlite://logs/app.db".to_string(),
    pool_size: 5,
    batch_size: 100,
    flush_interval_ms: 1000,
    archive_to_s3: false,
    archive_after_days: 30,
    s3_bucket: None,
    s3_region: Some("us-east-1".to_string()),
    table_name: "logs".to_string(),
    archive_format: "json".to_string(),
    parquet_config: inklog::config::ParquetConfig::default(),
};
```

---

### S3ArchiveConfig

S3 归档配置(需要 `aws` 功能)。

#### 定义

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct S3ArchiveConfig {
    pub enabled: bool,
    pub bucket: String,
    pub region: String,
    pub archive_interval_days: u32,
    pub local_retention_days: u32,
    pub local_retention_path: PathBuf,
    pub prefix: String,
    pub compression: CompressionType,
    pub storage_class: StorageClass,
    pub max_file_size_mb: u32,
    pub schedule_expression: Option<String>,
    pub force_path_style: bool,
    pub skip_bucket_validation: bool,
    pub access_key_id: SecretString,
    pub secret_access_key: SecretString,
    pub session_token: Option<SecretString>,
    pub endpoint_url: Option<String>,
    pub encryption: Option<EncryptionConfig>,
    pub archive_format: String,
}
```

#### 字段说明

| 字段 | 类型 | 默认值 | 描述 |
|------|------|----------|------|
| `enabled` | `bool` | `false` | 是否启用 S3 归档 |
| `bucket` | `String` | `"logs-archive"` | S3 存储桶名称 |
| `region` | `String` | `"us-east-1"` | AWS 区域 |
| `archive_interval_days` | `u32` | `7` | 归档间隔天数 |
| `schedule_expression` | `Option<String>` | `None` | Cron 表达式用于定时归档 |
| `local_retention_days` | `u32` | `30` | 本地保留天数 |
| `local_retention_path` | `PathBuf` | `"logs/archive_failures"` | 本地保留路径 |
| `prefix` | `String` | `"logs/"` | S3 对象键前缀 |
| `compression` | `CompressionType` | `Zstd` | 压缩类型 |
| `storage_class` | `StorageClass` | `Standard` | S3 存储类 |
| `max_file_size_mb` | `u32` | `100` | 单个归档文件最大大小(MB) |
| `force_path_style` | `bool` | `false` | 是否强制路径风格 |
| `skip_bucket_validation` | `bool` | `false` | 是否跳过存储桶验证 |
| `access_key_id` | `SecretString` | `default()` | AWS 访问密钥 ID |
| `secret_access_key` | `SecretString` | `default()` | AWS 密钥访问密钥 |
| `session_token` | `SecretString` | `default()` | AWS 会话令牌 |
| `endpoint_url` | `Option<String>` | `None` | 自定义 S3 端点 URL |
| `encryption` | `Option<EncryptionConfig>` | `None` | 服务器端加密配置 |
| `archive_format` | `String` | `"json"` | 归档文件格式(`json``parquet`|
| `parquet_config` | `ParquetConfig` | `default()` | Parquet 导出配置 |

**示例**
```rust
use inklog::S3ArchiveConfig;
use inklog::archive::{CompressionType, StorageClass};

let s3_config = S3ArchiveConfig {
    enabled: true,
    bucket: "my-log-bucket".to_string(),
    region: "us-west-2".to_string(),
    archive_interval_days: 7,
    local_retention_days: 30,
    prefix: "logs/".to_string(),
    compression: CompressionType::Zstd,
    storage_class: StorageClass::Standard,
    max_file_size_mb: 100,
    ..Default::default()
};
```

---

### HttpServerConfig

HTTP 服务器配置(需要 `http` 功能)。

#### 定义

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpServerConfig {
    pub enabled: bool,
    pub host: String,
    pub port: u16,
    pub metrics_path: String,
    pub health_path: String,
    pub error_mode: HttpErrorMode,
}
```

#### 字段说明

| 字段 | 类型 | 默认值 | 描述 |
|------|------|----------|------|
| `enabled` | `bool` | `false` | 是否启用 HTTP 服务器 |
| `host` | `String` | `"127.0.0.1"` | 监听主机地址 |
| `port` | `u16` | `9090` | 监听端口 |
| `metrics_path` | `String` | `"/metrics"` | Prometheus 指标端点路径 |
| `health_path` | `String` | `"/health"` | 健康检查端点路径 |
| `error_mode` | `HttpErrorMode` | `Panic` | 启动失败时的错误处理模式 |

#### HttpErrorMode 枚举

| 变体 | 描述 |
|------|------|
| `Panic` | 启动失败时 panic(默认) |
| `Warn` | 启动失败时记录警告,系统继续运行 |
| `Strict` | 启动失败时返回错误,阻止系统启动 |

**示例**
```rust
use inklog::config::{HttpServerConfig, HttpErrorMode};

let http_config = HttpServerConfig {
    enabled: true,
    host: "0.0.0.0".to_string(),
    port: 8080,
    metrics_path: "/metrics".to_string(),
    health_path: "/health".to_string(),
    error_mode: HttpErrorMode::Warn,
};
```

---

### PerformanceConfig

性能配置。

#### 定义

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceConfig {
    pub channel_capacity: usize,
    pub worker_threads: usize,
}
```

#### 字段说明

| 字段 | 类型 | 默认值 | 描述 |
|------|------|----------|------|
| `channel_capacity` | `usize` | `10000` | 日志通道容量 |
| `worker_threads` | `usize` | `3` | 工作线程数 |

**示例**
```rust
use inklog::config::PerformanceConfig;

let performance = PerformanceConfig {
    channel_capacity: 20000,
    worker_threads: 4,
};
```

---

### ParquetConfig

Parquet 导出配置(用于数据库归档)。

#### 定义

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParquetConfig {
    pub compression_level: i32,
    pub encoding: String,
    pub max_row_group_size: usize,
    pub max_page_size: usize,
    pub include_fields: Vec<String>,
}
```

#### 字段说明

| 字段 | 类型 | 默认值 | 描述 |
|------|------|----------|------|
| `compression_level` | `i32` | `3` | ZSTD 压缩级别(0-22) |
| `encoding` | `String` | `"PLAIN"` | 编码方式:`PLAIN``DICTIONARY``RLE` |
| `max_row_group_size` | `usize` | `10000` | Row Group 大小(行数) |
| `max_page_size` | `usize` | `1024 * 1024` | 页面大小(字节) |
| `include_fields` | `Vec<String>` | `[]` | 包含的字段列表(默认包含所有) |

**可用字段**
- `id` - 日志 ID
- `timestamp` - 时间戳
- `level` - 日志级别
- `target` - 日志目标
- `message` - 日志消息
- `fields` - 结构化字段
- `file` - 源文件
- `line` - 源行号
- `thread_id` - 线程 ID

**示例**
```rust
use inklog::config::ParquetConfig;

let parquet = ParquetConfig {
    compression_level: 5,
    encoding: "DICTIONARY".to_string(),
    max_row_group_size: 10000,
    max_page_size: 1024 * 1024,
    include_fields: vec![
        "id".to_string(),
        "timestamp".to_string(),
        "level".to_string(),
        "message".to_string(),
    ],
};
```

---

### DatabaseDriver

数据库驱动枚举。

#### 定义

```rust
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub enum DatabaseDriver {
    #[serde(rename = "postgres")]
    #[default]
    PostgreSQL,
    #[serde(rename = "mysql")]
    MySQL,
    #[serde(rename = "sqlite")]
    SQLite,
}
```

#### 变体说明

| 变体 | 字符串表示 | URL 示例 |
|------|------------|----------|
| `PostgreSQL` | `"postgres"` | `postgres://user:pass@localhost/logs` |
| `MySQL` | `"mysql"` | `mysql://user:pass@localhost/logs` |
| `SQLite` | `"sqlite"` | `sqlite://logs/app.db` |

**示例**
```rust
use inklog::config::DatabaseDriver;

let driver = DatabaseDriver::PostgreSQL;
```

---

## 错误类型

### InklogError

所有错误的枚举类型。

#### 定义

```rust
#[derive(Error, Debug)]
pub enum InklogError {
    #[error("Configuration error: {0}")]
    ConfigError(String),

    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),

    #[error("Serialization error: {0}")]
    SerializationError(#[from] serde_json::Error),

    #[error("Database error: {0}")]
    DatabaseError(String),

    #[error("Encryption error: {0}")]
    EncryptionError(String),

    #[error("Shutdown error: {0}")]
    Shutdown(String),

    #[error("Channel error: {0}")]
    ChannelError(String),

    #[error("S3 error: {0}")]
    S3Error(String),

    #[error("Compression error: {0}")]
    CompressionError(String),

    #[error("Runtime error: {0}")]
    RuntimeError(String),

    #[error("HTTP server error: {0}")]
    HttpServerError(String),

    #[error("Unknown error: {0}")]
    Unknown(String),
}
```

#### 变体说明

| 变体 | 描述 |
|------|------|
| `ConfigError` | 配置相关错误 |
| `IoError` | I/O 操作错误 |
| `SerializationError` | JSON/TOML 序列化错误 |
| `DatabaseError` | 数据库操作错误 |
| `EncryptionError` | 加密/解密错误 |
| `Shutdown` | 关闭过程中的错误 |
| `ChannelError` | 通道通信错误 |
| `S3Error` | AWS S3 操作错误 |
| `CompressionError` | 压缩/解压错误 |
| `RuntimeError` | 运行时错误 |
| `HttpServerError` | HTTP 服务器错误 |
| `Unknown` | 未知错误 |

**示例**
```rust
use inklog::InklogError;

fn example() -> Result<(), InklogError> {
    // 配置错误
    Err(InklogError::ConfigError("Invalid log level".to_string()))?;

    // I/O 错误
    Err(InklogError::IoError(std::io::Error::new(
        std::io::ErrorKind::NotFound,
        "File not found",
    )))?;

    Ok(())
}
```

---

## 健康监控类型

### HealthStatus

系统健康状态结构。

#### 定义

```rust
#[derive(Debug, Serialize)]
pub struct HealthStatus {
    pub overall_status: SinkStatus,
    pub sinks: HashMap<String, SinkHealth>,
    pub channel_usage: f64,
    pub uptime_seconds: u64,
    pub metrics: MetricsSnapshot,
}
```

#### 字段说明

| 字段 | 类型 | 描述 |
|------|------|------|
| `overall_status` | `SinkStatus` | 整体健康级别 |
| `sinks` | `HashMap<String, SinkHealth>` | 各 Sink 的健康状态 |
| `channel_usage` | `f64` | 通道使用率(0.0 - 1.0) |
| `uptime_seconds` | `u64` | 运行时间(秒) |
| `metrics` | `MetricsSnapshot` | 指标快照 |

---

### SinkStatus

Sink 组件状态枚举。

#### 定义

```rust
#[derive(Debug, Serialize, Clone, PartialEq, Default)]
pub enum SinkStatus {
    Healthy,
    Degraded { reason: String },
    Unhealthy { error: String },
    #[default]
    NotStarted,
}
```

#### 变体说明

| 变体 | 描述 |
|------|------|
| `Healthy` | Sink 正常运行 |
| `Degraded` | Sink 降级但仍在运行 |
| `Unhealthy` | Sink 失败且不可用 |
| `NotStarted` | Sink 尚未初始化 |

#### 方法

##### `is_operational`

返回 Sink 是否可操作(健康或降级但功能正常)。

**签名**
```rust
pub fn is_operational(&self) -> bool
```

**示例**
```rust
if status.is_operational() {
    println!("Sink 可用");
}
```

---

### SinkHealth

单个 Sink 的健康状态。

#### 定义

```rust
#[derive(Debug, Serialize, Clone)]
pub struct SinkHealth {
    pub status: SinkStatus,
    pub last_error: Option<String>,
    pub consecutive_failures: u32,
}
```

#### 字段说明

| 字段 | 类型 | 描述 |
|------|------|------|
| `status` | `SinkStatus` | 当前状态 |
| `last_error` | `Option<String>` | 最后一次错误的描述 |
| `consecutive_failures` | `u32` | 连续失败次数 |

---

### Metrics

指标收集器。

#### 定义

```rust
pub struct Metrics {
    pub(crate) logs_written_total: AtomicU64,
    pub(crate) logs_dropped_total: AtomicU64,
    pub(crate) channel_send_blocked_total: AtomicU64,
    pub(crate) sink_errors_total: AtomicU64,
    pub(crate) start_time: Instant,
    pub(crate) total_latency_us: AtomicU64,
    pub(crate) latency_count: AtomicU64,
    pub(crate) latency_histogram: Histogram,
    pub(crate) active_workers: Gauge,
    pub(crate) sink_health: Mutex<HashMap<String, SinkHealth>>,
}
```

#### 方法

##### `new`

创建新的 Metrics 实例。

**签名**
```rust
pub fn new() -> Self
```

**示例**
```rust
use inklog::Metrics;

let metrics = Metrics::new();
```

---

##### `logs_written`

返回成功写入的日志总数。

**签名**
```rust
pub fn logs_written(&self) -> u64
```

---

##### `inc_logs_written`

增加日志写入计数。

**签名**
```rust
pub fn inc_logs_written(&self)
```

---

##### `logs_dropped`

返回丢弃的日志总数。

**签名**
```rust
pub fn logs_dropped(&self) -> u64
```

---

##### `inc_logs_dropped`

增加日志丢弃计数。

**签名**
```rust
pub fn inc_logs_dropped(&self)
```

---

##### `sink_errors`

返回 Sink 错误总数。

**签名**
```rust
pub fn sink_errors(&self) -> u64
```

---

##### `inc_sink_error`

增加 Sink 错误计数。

**签名**
```rust
pub fn inc_sink_error(&self)
```

---

##### `record_latency`

记录处理延迟。

**签名**
```rust
pub fn record_latency(&self, duration: Duration)
```

---

##### `update_sink_health`

更新 Sink 的健康状态。

**签名**
```rust
pub fn update_sink_health(&self, name: &str, healthy: bool, error: Option<String>)
```

---

##### `get_status`

获取当前健康状态。

**签名**
```rust
pub fn get_status(&self, channel_len: usize, channel_cap: usize) -> HealthStatus
```

---

##### `export_prometheus`

导出 Prometheus 格式的指标。

**签名**
```rust
pub fn export_prometheus(&self) -> String
```

**示例**
```rust
let metrics = Metrics::new();
let prometheus_format = metrics.export_prometheus();
println!("{}", prometheus_format);
```

---

## 特征(Traits)

Inklog 实现了以下标准 Rust 特征:

### InklogConfig

实现了 `Serialize` 和 `Deserialize`,支持 TOML/JSON 配置。

### DatabaseDriver

实现了 `FromStr` 和 `Display`,支持字符串转换。

**示例**
```rust
// 从字符串解析
let driver: DatabaseDriver = "postgres".parse().unwrap();

// 转换为字符串
let driver_str = driver.to_string(); // "postgres"
```

---

**[返回顶部](#inklog-api-参考文档)**