loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
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
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
use std::{
    borrow::Cow,
    cell::Cell,
    fmt::{self, Display},
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
    time::{Duration, Instant},
};

use axum::{
    Router,
    extract::{MatchedPath, Request, State},
    http::{HeaderName, HeaderValue, Method, Response, StatusCode, Uri},
    middleware::{self, Next},
    response::Response as AxumResponse,
};
use serde::{Serialize, Serializer, ser::SerializeMap};
use thiserror::Error;
use tower_http::catch_panic::CatchPanicLayer;

use super::{
    OperationKind, RequestId, RequestLogContext, RequestLoggingLimits, RequestSubject,
    TrustedSubject,
    context::scope_request_log,
    json_format::{ERROR_FIELD, REQUEST_CONTEXT_FIELD, REQUEST_HEADERS_FIELD},
    panic_recovery::{PanicRecoveryConfig, response_for_panic},
};
use crate::web::response::ErrorLogMetadata;

// f64 的有效尾数为 53 位;使用同等精度的整数阈值可避免每次请求执行浮点除法。
const SUCCESS_SAMPLE_SCALE: u64 = 1_u64 << 53;
const SUCCESS_SAMPLE_SCALE_FLOAT: f64 = 9_007_199_254_740_992.0;
const SAMPLE_THREAD_SEED_INCREMENT: u64 = 0x9e37_79b9_7f4a_7c15;
static SAMPLE_THREAD_SEED: AtomicU64 = AtomicU64::new(SAMPLE_THREAD_SEED_INCREMENT);

thread_local! {
    // 全局原子只在线程首次采样时访问一次,正常请求使用线程本地状态,避免多核缓存行竞争。
    static SAMPLE_STATE: Cell<u64> = Cell::new(mix_sample_value(
        SAMPLE_THREAD_SEED.fetch_add(SAMPLE_THREAD_SEED_INCREMENT, Ordering::Relaxed),
    ));
}

struct RequestContextJson<'context>(&'context RequestLogContext);

impl Display for RequestContextJson<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_json(formatter, self.0)
    }
}

/// 单请求日志配置。
#[derive(Clone, Debug)]
#[must_use = "配置需要传给 RouterLoggingExt 才会生效"]
#[allow(clippy::struct_excessive_bools)]
pub struct RequestLoggingConfig {
    request_id_header: HeaderName,
    request_id_max_length: usize,
    trusted_subject_header: Option<HeaderName>,
    trusted_subject_kind: Option<String>,
    trusted_subject_max_length: usize,
    included_headers: Vec<HeaderName>,
    redacted_headers: Vec<HeaderName>,
    include_query: bool,
    panic_recovery: Option<PanicRecoveryConfig>,
    skipped_success_paths: Vec<String>,
    skipped_success_prefixes: Vec<String>,
    slow_request_threshold: Option<Duration>,
    success_sample_threshold: u64,
    always_log_errors: bool,
    quiet_queries: bool,
    log_slow_queries: bool,
    always_log_commands: bool,
    expose_context_in_response: bool,
    limits: RequestLoggingLimits,
}

impl Default for RequestLoggingConfig {
    fn default() -> Self {
        Self {
            request_id_header: HeaderName::from_static("x-request-id"),
            request_id_max_length: 128,
            trusted_subject_header: None,
            trusted_subject_kind: None,
            trusted_subject_max_length: 128,
            included_headers: Vec::new(),
            redacted_headers: vec![
                HeaderName::from_static("authorization"),
                HeaderName::from_static("cookie"),
                HeaderName::from_static("set-cookie"),
                HeaderName::from_static("x-api-key"),
            ],
            // 查询参数可能包含令牌或个人信息,默认不写入日志。
            include_query: false,
            panic_recovery: Some(PanicRecoveryConfig::default()),
            skipped_success_paths: vec!["/health".into(), "/metrics".into()],
            skipped_success_prefixes: vec!["/static/".into()],
            slow_request_threshold: Some(Duration::from_millis(400)),
            success_sample_threshold: SUCCESS_SAMPLE_SCALE,
            always_log_errors: true,
            quiet_queries: false,
            log_slow_queries: true,
            always_log_commands: false,
            expose_context_in_response: false,
            limits: RequestLoggingLimits::default(),
        }
    }
}

/// 请求日志配置校验错误。
#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum RequestLoggingConfigError {
    /// 数值必须大于零。
    #[error("{name}必须大于 0")]
    NonPositive { name: &'static str },
    /// 采样率超出合法范围。
    #[error("成功请求日志采样率必须是 0.0 到 1.0 之间的有限数值")]
    InvalidSampleRate,
}

impl RequestLoggingConfig {
    /// 创建默认配置。
    pub fn new() -> Self {
        Self::default()
    }

    /// 指定请求 ID 请求头。
    pub fn with_request_id_header(mut self, header: HeaderName) -> Self {
        self.request_id_header = header;
        self
    }

    /// 设置请求 ID 最大字节长度,默认为 128。
    ///
    /// # Panics
    ///
    /// `max_length` 为零时触发 panic;外部配置应使用 [`Self::try_request_id_max_length`]。
    pub fn request_id_max_length(mut self, max_length: usize) -> Self {
        assert!(max_length > 0, "请求 ID 最大长度必须大于 0");
        self.request_id_max_length = max_length;
        self
    }

    /// 尝试设置请求 ID 最大字节长度。
    ///
    /// # Errors
    ///
    /// `max_length` 为零时返回配置错误。
    pub fn try_request_id_max_length(
        mut self,
        max_length: usize,
    ) -> Result<Self, RequestLoggingConfigError> {
        if max_length == 0 {
            return Err(RequestLoggingConfigError::NonPositive {
                name: "请求 ID 最大长度",
            });
        }
        self.request_id_max_length = max_length;
        Ok(self)
    }

    /// 指定一个已由应用或网关确认可信的主体 ID 请求头。
    ///
    /// 工具库只负责读取和传播,不负责验证该请求头的来源。应用必须保证外部请求无法绕过
    /// 可信边界直接伪造它。未配置时不会读取任何主体请求头。
    pub fn trusted_subject_header(mut self, header: HeaderName) -> Self {
        self.trusted_subject_header = Some(header);
        self
    }

    /// 关闭从请求头提取可信主体。
    pub fn without_trusted_subject(mut self) -> Self {
        self.trusted_subject_header = None;
        self.trusted_subject_kind = None;
        self
    }

    /// 为从可信请求头读取的主体设置通用类型。
    pub fn trusted_subject_kind(mut self, kind: impl Into<String>) -> Self {
        self.trusted_subject_kind = Some(kind.into());
        self
    }

    /// 设置可信主体 ID 的最大字节长度,默认为 128。
    ///
    /// # Panics
    ///
    /// 当长度为 0 时触发 panic。
    pub fn trusted_subject_max_length(mut self, max_length: usize) -> Self {
        assert!(max_length > 0, "可信主体 ID 最大长度必须大于 0");
        self.trusted_subject_max_length = max_length;
        self
    }

    /// 尝试设置可信主体 ID 的最大字节长度。
    ///
    /// # Errors
    ///
    /// `max_length` 为零时返回配置错误。
    pub fn try_trusted_subject_max_length(
        mut self,
        max_length: usize,
    ) -> Result<Self, RequestLoggingConfigError> {
        if max_length == 0 {
            return Err(RequestLoggingConfigError::NonPositive {
                name: "可信主体 ID 最大长度",
            });
        }
        self.trusted_subject_max_length = max_length;
        Ok(self)
    }

    /// 增加一个允许记录的请求头;不会记录未明确指定的请求头。
    pub fn include_header(mut self, header: HeaderName) -> Self {
        if !self.included_headers.contains(&header) {
            self.included_headers.push(header);
        }
        self
    }

    /// 增加多个允许记录的请求头;不会记录未明确指定的请求头。
    pub fn include_headers<I>(mut self, headers: I) -> Self
    where
        I: IntoIterator<Item = HeaderName>,
    {
        for header in headers {
            if !self.included_headers.contains(&header) {
                self.included_headers.push(header);
            }
        }
        self
    }

    /// 清空请求头白名单。
    pub fn without_headers(mut self) -> Self {
        self.included_headers.clear();
        self
    }

    /// 增加一个必须脱敏的请求头。
    ///
    /// 即使该请求头同时出现在记录白名单中,日志也只会输出 `[已脱敏]`。
    pub fn redact_header(mut self, header: HeaderName) -> Self {
        if !self.redacted_headers.contains(&header) {
            self.redacted_headers.push(header);
        }
        self
    }

    /// 设置是否记录查询字符串。
    pub const fn include_query(mut self, include: bool) -> Self {
        self.include_query = include;
        self
    }

    /// 成功响应命中指定路径时不输出日志;错误和慢请求仍按其他策略处理。
    ///
    /// 同时支持实际路径(如 `/users/1`)和 Axum 匹配路径(如 `/users/{id}`),
    /// 查询字符串不参与匹配。
    pub fn skip_success_path(mut self, path: impl Into<String>) -> Self {
        let path = path.into();
        if !self.skipped_success_paths.contains(&path) {
            self.skipped_success_paths.push(path);
        }
        self
    }

    /// 成功响应命中指定路径前缀时不输出日志;查询字符串不参与匹配。
    pub fn skip_success_prefix(mut self, prefix: impl Into<String>) -> Self {
        let prefix = prefix.into();
        if !self.skipped_success_prefixes.contains(&prefix) {
            self.skipped_success_prefixes.push(prefix);
        }
        self
    }

    /// 清空默认和自定义的成功请求跳过路径。
    pub fn clear_skipped_success_paths(mut self) -> Self {
        self.skipped_success_paths.clear();
        self
    }

    /// 清空默认和自定义的成功请求跳过前缀。
    pub fn clear_skipped_success_prefixes(mut self) -> Self {
        self.skipped_success_prefixes.clear();
        self
    }

    /// 设置慢请求阈值;达到或超过该耗时的请求始终记录,并标记为慢请求。
    pub const fn slow_request_threshold(mut self, threshold: Duration) -> Self {
        self.slow_request_threshold = Some(threshold);
        self
    }

    /// 关闭慢请求识别。
    pub const fn without_slow_request_threshold(mut self) -> Self {
        self.slow_request_threshold = None;
        self
    }

    /// 设置普通成功请求的日志采样率,取值范围为 `0.0..=1.0`。
    ///
    /// `1.0` 表示全部记录,`0.0` 表示全部跳过。错误和慢请求可绕过采样策略。
    ///
    /// # Panics
    ///
    /// 当 `rate` 不是有限数值或不在 `0.0..=1.0` 范围内时触发 panic。
    pub fn success_sample_rate(mut self, rate: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&rate),
            "成功请求日志采样率必须在 0.0 到 1.0 之间"
        );
        self.success_sample_threshold = success_sample_threshold(rate);
        self
    }

    /// 尝试设置普通成功请求的日志采样率。
    ///
    /// # Errors
    ///
    /// `rate` 不是有限数值或不在 `0.0..=1.0` 范围内时返回配置错误。
    pub fn try_success_sample_rate(mut self, rate: f64) -> Result<Self, RequestLoggingConfigError> {
        if !rate.is_finite() || !(0.0..=1.0).contains(&rate) {
            return Err(RequestLoggingConfigError::InvalidSampleRate);
        }
        self.success_sample_threshold = success_sample_threshold(rate);
        Ok(self)
    }

    /// 设置错误响应是否忽略路径过滤和成功采样,始终输出日志。
    pub const fn always_log_errors(mut self, always: bool) -> Self {
        self.always_log_errors = always;
        self
    }

    /// 设置是否静默查询操作。
    ///
    /// 启用后,查询成功和没有内部诊断的预期业务错误不输出;慢查询是否输出由
    /// `log_slow_queries` 控制,系统错误和 panic 仍受 `always_log_errors` 控制。
    /// 未显式设置操作时,GET、HEAD 和 OPTIONS 被视为查询。
    pub const fn quiet_queries(mut self, quiet: bool) -> Self {
        self.quiet_queries = quiet;
        self
    }

    /// 设置静默查询时是否仍记录慢查询,默认为 `true`。
    pub const fn log_slow_queries(mut self, enabled: bool) -> Self {
        self.log_slow_queries = enabled;
        self
    }

    /// 设置命令操作是否绕过路径过滤和成功采样,始终输出。
    ///
    /// 未显式设置操作时,GET、HEAD、OPTIONS 之外的方法被视为命令。
    pub const fn always_log_commands(mut self, always: bool) -> Self {
        self.always_log_commands = always;
        self
    }

    /// 设置是否把最终请求上下文放入响应扩展,默认关闭以减少一次 `Arc` 克隆。
    pub const fn expose_context_in_response(mut self, expose: bool) -> Self {
        self.expose_context_in_response = expose;
        self
    }

    /// 设置请求日志的容量和字段大小限制。
    pub const fn with_limits(mut self, limits: RequestLoggingLimits) -> Self {
        self.limits = limits;
        self
    }

    /// 使用指定配置捕获 handler 或内层 middleware 中的 panic。
    pub fn with_panic_recovery_config(mut self, config: PanicRecoveryConfig) -> Self {
        self.panic_recovery = Some(config);
        self
    }

    /// 关闭 panic 捕获。
    pub fn without_panic_recovery(mut self) -> Self {
        self.panic_recovery = None;
        self
    }

    fn should_skip_success(&self, metadata: &RequestLogMetadata) -> bool {
        let path = metadata.uri.path();
        let route = metadata.route.as_ref().map(MatchedPath::as_str);

        self.skipped_success_paths
            .iter()
            .any(|skipped| skipped == path || route.is_some_and(|route| skipped == route))
            || self.skipped_success_prefixes.iter().any(|prefix| {
                path.starts_with(prefix) || route.is_some_and(|route| route.starts_with(prefix))
            })
    }

    fn is_slow_request(&self, latency: Duration) -> bool {
        self.slow_request_threshold
            .is_some_and(|threshold| latency >= threshold)
    }

    fn should_sample_success(&self) -> bool {
        if self.success_sample_threshold == SUCCESS_SAMPLE_SCALE {
            return true;
        }
        if self.success_sample_threshold == 0 {
            return false;
        }

        let value = next_sample_value();
        (value >> 11) < self.success_sample_threshold
    }
}

const fn mix_sample_value(mut value: u64) -> u64 {
    value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
    value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
    value ^ (value >> 31)
}

fn next_sample_value() -> u64 {
    SAMPLE_STATE.with(|state| {
        // xorshift64* 只修改当前工作线程的状态,不需要逐请求同步。
        let mut value = state.get();
        value ^= value >> 12;
        value ^= value << 25;
        value ^= value >> 27;
        state.set(value);
        value.wrapping_mul(0x2545_f491_4f6c_dd1d)
    })
}

#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
fn success_sample_threshold(rate: f64) -> u64 {
    (rate * SUCCESS_SAMPLE_SCALE_FLOAT).round() as u64
}

struct RequestLogMetadata {
    method: Method,
    uri: Uri,
    route: Option<MatchedPath>,
    request_id: RequestId,
    request_id_header_value: HeaderValue,
    headers: Vec<CapturedHeader>,
    max_header_value_bytes: usize,
}

struct CapturedHeader {
    name: HeaderName,
    value: HeaderValue,
    redacted: bool,
}

impl RequestLogMetadata {
    fn from_request<B>(
        request: &mut axum::http::Request<B>,
        config: &RequestLoggingConfig,
        request_log: Option<&RequestLogContext>,
    ) -> Self {
        let request_id = request
            .headers()
            .get(&config.request_id_header)
            .and_then(|value| value.to_str().ok())
            .map(str::trim)
            .filter(|value| !value.is_empty() && value.len() <= config.request_id_max_length)
            .map_or_else(
                || RequestId::new(uuid::Uuid::now_v7().to_string()),
                |value| RequestId::new(value.to_owned()),
            );
        let request_id_header_value = HeaderValue::from_str(request_id.as_str())
            .expect("UUID 或已校验的请求 ID 始终是合法请求头值");

        let trusted_subject = config
            .trusted_subject_header
            .as_ref()
            .and_then(|header| request.headers().get(header))
            .and_then(|value| value.to_str().ok())
            .map(str::trim)
            .filter(|value| !value.is_empty() && value.len() <= config.trusted_subject_max_length)
            .map(|value| {
                let mut subject = RequestSubject::new(value);
                if let Some(kind) = &config.trusted_subject_kind {
                    subject = subject.with_kind(kind.clone());
                }
                subject
            });

        let headers = config
            .included_headers
            .iter()
            .filter_map(|name| {
                request
                    .headers()
                    .get(name)
                    .filter(|value| value.to_str().is_ok())
                    .map(|value| CapturedHeader {
                        name: name.clone(),
                        value: value.clone(),
                        redacted: config.redacted_headers.contains(name),
                    })
            })
            .collect();

        request.extensions_mut().insert(request_id.clone());
        if let Some(subject) = trusted_subject {
            if let Some(request_log) = request_log {
                request_log.set_subject(subject.clone());
            }
            request
                .extensions_mut()
                .insert(TrustedSubject::new(subject));
        }

        Self {
            method: request.method().clone(),
            uri: request.uri().clone(),
            route: request.extensions().get::<MatchedPath>().cloned(),
            request_id,
            request_id_header_value,
            headers,
            max_header_value_bytes: config.limits.max_header_value_bytes,
        }
    }

    fn route(&self) -> &str {
        self.route
            .as_ref()
            .map_or_else(|| self.uri.path(), MatchedPath::as_str)
    }

    fn request_id(&self) -> &str {
        self.request_id.as_str()
    }

    fn headers_for_log(&self) -> Option<RequestHeadersJson<'_>> {
        (!self.headers.is_empty()).then_some(RequestHeadersJson {
            headers: &self.headers,
            max_value_bytes: self.max_header_value_bytes,
        })
    }
}

struct RequestHeadersJson<'headers> {
    headers: &'headers [CapturedHeader],
    max_value_bytes: usize,
}

impl Serialize for RequestHeadersJson<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(None)?;
        for captured in self.headers {
            let raw_value = if captured.redacted {
                "[已脱敏]"
            } else {
                captured.value.to_str().expect("捕获请求头时已校验 UTF-8")
            };
            if raw_value.len() <= self.max_value_bytes {
                map.serialize_entry(captured.name.as_str(), raw_value)?;
            } else {
                let mut truncated = raw_value.to_owned();
                super::context::truncate_utf8(&mut truncated, self.max_value_bytes);
                map.serialize_entry(captured.name.as_str(), &truncated)?;
            }
        }
        map.end()
    }
}

impl Display for RequestHeadersJson<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_json(formatter, self)
    }
}

struct ErrorJson<'error>(&'error ErrorLogMetadata);

impl Display for ErrorJson<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_json(formatter, self.0)
    }
}

struct RequestUri<'a> {
    uri: &'a Uri,
    include_query: bool,
    max_bytes: usize,
}

impl Display for RequestUri<'_> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let raw = if self.include_query {
            Cow::Owned(self.uri.to_string())
        } else {
            Cow::Borrowed(self.uri.path())
        };
        if raw.len() <= self.max_bytes {
            formatter.write_str(raw.as_ref())
        } else {
            let mut truncated = raw.into_owned();
            super::context::truncate_utf8(&mut truncated, self.max_bytes);
            formatter.write_str(&truncated)
        }
    }
}

#[derive(Clone, Copy)]
enum RequestEventLevel {
    Info,
    Warn,
    Error,
}

impl RequestEventLevel {
    fn is_enabled(self) -> bool {
        match self {
            Self::Info => tracing::event_enabled!(tracing::Level::INFO),
            Self::Warn => tracing::event_enabled!(tracing::Level::WARN),
            Self::Error => tracing::event_enabled!(tracing::Level::ERROR),
        }
    }
}

struct RequestEvent<'a> {
    metadata: &'a RequestLogMetadata,
    include_query: bool,
    max_uri_bytes: usize,
    status: StatusCode,
    handler_latency_ms: f64,
    is_slow: bool,
    operation_kind: &'static str,
    outcome: &'static str,
    request_context: Option<&'a RequestLogContext>,
}

macro_rules! emit_request_event {
    ($level:expr, $event:expr; $($extra:tt)*) => {{
        let uri = RequestUri {
            uri: &$event.metadata.uri,
            include_query: $event.include_query,
            max_bytes: $event.max_uri_bytes,
        };
        let headers = $event
            .metadata
            .headers_for_log()
            .map(tracing::field::display);
        let request_context = $event
            .request_context
            .map(RequestContextJson)
            .map(tracing::field::display);
        tracing::event!(
            $level,
            method = %$event.metadata.method,
            route = %$event.metadata.route(),
            path = %$event.metadata.uri.path(),
            uri = %uri,
            request_id = %$event.metadata.request_id(),
            event = "request.completed",
            operation_kind = $event.operation_kind,
            { REQUEST_HEADERS_FIELD } = headers,
            status = $event.status.as_u16(),
            outcome = $event.outcome,
            handler_latency_ms = $event.handler_latency_ms,
            slow_request = $event.is_slow,
            { REQUEST_CONTEXT_FIELD } = request_context,
            $($extra)*
            "请求处理完成"
        );
    }};
}

/// 为 Axum Router 安装单请求日志能力。
pub trait RouterLoggingExt<S> {
    /// 使用默认配置安装请求日志。
    fn with_request_logging(self) -> Router<S>;

    /// 使用指定配置安装请求日志。
    fn with_request_logging_config(self, config: RequestLoggingConfig) -> Router<S>;

    /// 使用默认配置安装轻量访问日志,不创建或注入请求日志上下文。
    fn with_access_logging(self) -> Router<S>;

    /// 使用指定配置安装轻量访问日志,不创建或注入请求日志上下文。
    fn with_access_logging_config(self, config: RequestLoggingConfig) -> Router<S>;
}

impl<S> RouterLoggingExt<S> for Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    fn with_request_logging(self) -> Self {
        self.with_request_logging_config(RequestLoggingConfig::default())
    }

    fn with_request_logging_config(self, config: RequestLoggingConfig) -> Self {
        install_request_logging(self, config, true)
    }

    fn with_access_logging(self) -> Self {
        self.with_access_logging_config(RequestLoggingConfig::default())
    }

    fn with_access_logging_config(self, config: RequestLoggingConfig) -> Self {
        install_request_logging(self, config, false)
    }
}

fn install_request_logging<S>(
    router: Router<S>,
    config: RequestLoggingConfig,
    include_context: bool,
) -> Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    // 恢复层包裹实际业务处理,将 panic 转为带内部错误元数据的统一响应。
    let router = if let Some(panic_config) = config.panic_recovery.clone() {
        router.layer(CatchPanicLayer::custom(move |payload| {
            response_for_panic(payload, &panic_config)
        }))
    } else {
        router
    };

    // 配置由所有请求共享;常量泛型会分别生成完整模式和轻量模式,消除逐请求模式判断。
    let config = Arc::new(config);
    if include_context {
        router.layer(middleware::from_fn_with_state(
            config,
            request_logging_middleware::<true>,
        ))
    } else {
        router.layer(middleware::from_fn_with_state(
            config,
            request_logging_middleware::<false>,
        ))
    }
}

async fn request_logging_middleware<const INCLUDE_CONTEXT: bool>(
    State(config): State<Arc<RequestLoggingConfig>>,
    mut request: Request,
    next: Next,
) -> AxumResponse {
    let request_log =
        INCLUDE_CONTEXT.then(|| RequestLogContext::with_limits(config.limits.clone()));
    if let Some(request_log) = &request_log {
        request.extensions_mut().insert(request_log.clone());
    }
    let metadata = RequestLogMetadata::from_request(&mut request, &config, request_log.as_ref());
    let started_at = Instant::now();
    let mut response = if let Some(request_log) = &request_log {
        scope_request_log(request_log.clone(), next.run(request)).await
    } else {
        next.run(request).await
    };
    let latency = started_at.elapsed();

    // 先执行过滤和采样,只有真正需要输出时才构造 JSON 字段和 tracing event。
    log_response(&response, latency, &metadata, request_log.as_ref(), &config);

    if config.expose_context_in_response
        && let Some(request_log) = request_log
    {
        response.extensions_mut().insert(request_log);
    }
    response.headers_mut().insert(
        config.request_id_header.clone(),
        metadata.request_id_header_value.clone(),
    );
    response
}

fn log_response<B>(
    response: &Response<B>,
    latency: Duration,
    metadata: &RequestLogMetadata,
    request_log: Option<&RequestLogContext>,
    config: &RequestLoggingConfig,
) {
    let status = response.status();
    let error = response.extensions().get::<ErrorLogMetadata>();
    let request_decision = request_log.map(RequestLogContext::decision);
    let has_request_failures = request_decision.is_some_and(|decision| decision.has_failures);
    let is_error = error.is_some()
        || status.is_client_error()
        || status.is_server_error()
        || has_request_failures;
    let is_system_error = error.is_some_and(ErrorLogMetadata::has_internal_diagnostics)
        || (error.is_none() && status.is_server_error())
        || has_request_failures;
    let operation_kind = request_decision
        .and_then(|decision| decision.operation_kind)
        .unwrap_or_else(|| operation_kind_from_method(&metadata.method));

    let is_slow = config.is_slow_request(latency);

    if config.quiet_queries
        && operation_kind == OperationKind::Query
        && !is_system_error
        && !(is_slow && config.log_slow_queries)
    {
        return;
    }

    let bypass_regular_policy = is_slow
        || (is_error && config.always_log_errors)
        || (operation_kind == OperationKind::Command && config.always_log_commands);

    let level = if is_system_error {
        RequestEventLevel::Error
    } else if error.is_some() || status.is_client_error() || is_slow {
        RequestEventLevel::Warn
    } else {
        RequestEventLevel::Info
    };
    if !level.is_enabled() {
        return;
    }

    // 只有启用对应日志级别且没有强制记录理由时,才执行路径匹配和随机采样。
    if !bypass_regular_policy
        && (config.should_skip_success(metadata) || !config.should_sample_success())
    {
        return;
    }

    let handler_latency_ms = latency.as_secs_f64() * 1_000.0;
    let event = RequestEvent {
        metadata,
        include_query: config.include_query,
        max_uri_bytes: config.limits.max_uri_bytes,
        status,
        handler_latency_ms,
        is_slow,
        operation_kind: match operation_kind {
            OperationKind::Query => "query",
            OperationKind::Command => "command",
        },
        outcome: if is_error { "failure" } else { "success" },
        request_context: if request_decision.is_some_and(|decision| decision.is_empty) {
            None
        } else {
            request_log
        },
    };

    emit_response_event(&event, error, level);
}

fn operation_kind_from_method(method: &Method) -> OperationKind {
    if method == Method::GET || method == Method::HEAD || method == Method::OPTIONS {
        OperationKind::Query
    } else {
        OperationKind::Command
    }
}

fn emit_response_event(
    event: &RequestEvent<'_>,
    error: Option<&ErrorLogMetadata>,
    level: RequestEventLevel,
) {
    if let Some(error) = error {
        match level {
            RequestEventLevel::Error => emit_request_event!(
                tracing::Level::ERROR,
                event;
                { ERROR_FIELD } = %ErrorJson(error),
            ),
            RequestEventLevel::Warn => emit_request_event!(
                tracing::Level::WARN,
                event;
                { ERROR_FIELD } = %ErrorJson(error),
            ),
            RequestEventLevel::Info => emit_request_event!(
                tracing::Level::INFO,
                event;
                { ERROR_FIELD } = %ErrorJson(error),
            ),
        }
    } else {
        match level {
            RequestEventLevel::Error => {
                emit_request_event!(tracing::Level::ERROR, event;);
            }
            RequestEventLevel::Warn => {
                emit_request_event!(tracing::Level::WARN, event;);
            }
            RequestEventLevel::Info => {
                emit_request_event!(tracing::Level::INFO, event;);
            }
        }
    }
}

fn write_json<T>(formatter: &mut fmt::Formatter<'_>, value: &T) -> fmt::Result
where
    T: Serialize + ?Sized,
{
    serde_json::to_writer(FormatterWriteAdapter(formatter), value).map_err(|_| fmt::Error)
}

struct FormatterWriteAdapter<'formatter, 'buffer>(&'formatter mut fmt::Formatter<'buffer>);

impl std::io::Write for FormatterWriteAdapter<'_, '_> {
    fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
        let value = std::str::from_utf8(buffer)
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
        self.0
            .write_str(value)
            .map_err(|_| std::io::Error::other("写入 JSON 日志字段失败"))?;
        Ok(buffer.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::{
        io::{self, Write},
        sync::Mutex,
    };

    use axum::{
        Extension,
        body::Body,
        http::{
            Request, StatusCode,
            header::{CONTENT_TYPE, USER_AGENT},
        },
        routing::{get, post},
    };
    use http_body_util::BodyExt;
    use tower::ServiceExt;
    use tracing_subscriber::fmt::{MakeWriter, format::JsonFields};

    use super::*;

    #[derive(Clone, Default)]
    struct SharedWriter {
        bytes: Arc<Mutex<Vec<u8>>>,
    }

    struct SharedWriterGuard {
        bytes: Arc<Mutex<Vec<u8>>>,
    }

    impl Write for SharedWriterGuard {
        fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
            self.bytes
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .extend_from_slice(buffer);
            Ok(buffer.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    impl<'a> MakeWriter<'a> for SharedWriter {
        type Writer = SharedWriterGuard;

        fn make_writer(&'a self) -> Self::Writer {
            SharedWriterGuard {
                bytes: Arc::clone(&self.bytes),
            }
        }
    }

    impl SharedWriter {
        fn output(&self) -> String {
            let bytes = self
                .bytes
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .clone();
            String::from_utf8(bytes).unwrap()
        }
    }

    fn set_json_subscriber(
        writer: &SharedWriter,
        max_level: tracing::Level,
    ) -> tracing::subscriber::DefaultGuard {
        let subscriber = tracing_subscriber::fmt()
            .fmt_fields(JsonFields::new())
            .event_format(super::super::StructuredJsonFormatter::new())
            .with_max_level(max_level)
            .with_writer(writer.clone())
            .finish();
        tracing::subscriber::set_default(subscriber)
    }

    #[test]
    fn structured_formatter_preserves_regular_fields_and_current_span() {
        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
        let span = tracing::info_span!("业务跨度", user_id = 1001_u64);

        span.in_scope(|| {
            tracing::info!(count = 2_u64, detail = %"带\"引号", "普通日志");
        });

        let output = writer.output();
        assert_eq!(output.lines().count(), 1);
        let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        assert_eq!(log["fields"]["message"], "普通日志");
        assert_eq!(log["fields"]["count"], 2);
        assert_eq!(log["fields"]["detail"], "带\"引号");
        assert_eq!(log["span"]["name"], "业务跨度");
        assert_eq!(log["span"]["user_id"], 1001);
    }

    #[test]
    fn cloned_context_shares_fields() {
        let context = RequestLogContext::new();
        let cloned = context.clone();

        context.insert("user_id", 1001);
        cloned.insert("result", "成功");

        let snapshot = context.snapshot();
        assert_eq!(snapshot.get("user_id").map(String::as_str), Some("1001"));
        assert_eq!(snapshot.get("result").map(String::as_str), Some("成功"));
        assert_eq!(cloned.remove("result").as_deref(), Some("成功"));
        assert!(!context.snapshot().contains_key("result"));
    }

    #[test]
    fn context_supports_concurrent_writers_without_losing_fields() {
        let context = RequestLogContext::with_limits(RequestLoggingLimits::new().max_fields(2_000));
        let threads = (0..8)
            .map(|thread_id| {
                let context = context.clone();
                std::thread::spawn(move || {
                    for field_id in 0..250 {
                        context.insert(format!("{thread_id}:{field_id}"), field_id);
                    }
                })
            })
            .collect::<Vec<_>>();

        for thread in threads {
            thread.join().unwrap();
        }

        assert_eq!(context.snapshot().len(), 2_000);
    }

    #[test]
    fn config_does_not_duplicate_headers() {
        let config = RequestLoggingConfig::default()
            .include_header(USER_AGENT)
            .include_headers([USER_AGENT, CONTENT_TYPE]);
        assert_eq!(config.included_headers.len(), 2);

        let config = config.without_headers();
        assert!(config.included_headers.is_empty());
    }

    #[test]
    fn default_config_uses_recommended_log_policy() {
        let config = RequestLoggingConfig::default();

        assert!(config.included_headers.is_empty());
        assert_eq!(config.skipped_success_paths, ["/health", "/metrics"]);
        assert_eq!(config.skipped_success_prefixes, ["/static/"]);
        assert_eq!(
            config.slow_request_threshold,
            Some(Duration::from_millis(400))
        );
        assert_eq!(config.success_sample_threshold, SUCCESS_SAMPLE_SCALE);
        assert!(config.always_log_errors);

        let config = config.without_panic_recovery();
        assert!(config.panic_recovery.is_none());
    }

    #[test]
    fn fallible_subject_length_rejects_zero() {
        assert!(
            RequestLoggingConfig::new()
                .try_trusted_subject_max_length(0)
                .is_err()
        );
    }

    #[test]
    fn partial_success_sampling_is_stable() {
        let config = RequestLoggingConfig::new().success_sample_rate(0.25);
        let sampled = (0..10_000)
            .filter(|_| config.should_sample_success())
            .count();

        assert!((2_300..=2_700).contains(&sampled));
    }

    #[test]
    #[should_panic(expected = "成功请求日志采样率必须在 0.0 到 1.0 之间")]
    fn invalid_success_sample_rate_panics() {
        let _ = RequestLoggingConfig::new().success_sample_rate(1.1);
    }

    #[test]
    fn sampling_boundaries_are_exact_and_non_finite_rates_are_rejected() {
        let never = RequestLoggingConfig::new().success_sample_rate(0.0);
        let always = RequestLoggingConfig::new().success_sample_rate(1.0);

        assert!((0..1_000).all(|_| !never.should_sample_success()));
        assert!((0..1_000).all(|_| always.should_sample_success()));
        assert!(
            std::panic::catch_unwind(|| {
                RequestLoggingConfig::new().success_sample_rate(f64::NAN)
            })
            .is_err()
        );
        assert!(
            std::panic::catch_unwind(|| {
                RequestLoggingConfig::new().success_sample_rate(f64::INFINITY)
            })
            .is_err()
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn one_request_emits_one_json_log() {
        async fn handler(Extension(context): Extension<RequestLogContext>) -> &'static str {
            context.insert("operation", "测试请求");
            "完成"
        }

        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);

        let app = Router::new()
            .route("/test", get(handler))
            .with_request_logging();
        let response = app
            .oneshot(Request::get("/test").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), axum::http::StatusCode::OK);
        let output = writer.output();
        assert_eq!(output.lines().count(), 1);
        assert!(output.contains("测试请求"));

        let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        assert!(log.get("span").is_none());
        assert_eq!(log["fields"]["method"], "GET");
        assert_eq!(log["fields"]["route"], "/test");
        assert_eq!(log["fields"]["path"], "/test");
        assert_eq!(log["fields"]["uri"], "/test");
        let request_id = log["fields"]["request_id"].as_str().unwrap();
        assert!(!request_id.is_empty());
        assert_eq!(
            response
                .headers()
                .get("x-request-id")
                .unwrap()
                .to_str()
                .unwrap(),
            request_id
        );
        assert_eq!(log["fields"]["request_context"]["operation"], "测试请求");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn access_logging_does_not_create_request_context() {
        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);

        let app = Router::new()
            .route("/test", get(|| async { "完成" }))
            .with_access_logging();
        let response = app
            .oneshot(Request::get("/test").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert!(response.extensions().get::<RequestLogContext>().is_none());

        let output = writer.output();
        assert_eq!(output.lines().count(), 1);
        let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        assert!(log["fields"].get("request_context").is_none());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn complete_context_is_exposed_in_response_only_when_enabled() {
        for (expose, expected) in [(false, false), (true, true)] {
            let config = RequestLoggingConfig::new()
                .success_sample_rate(0.0)
                .expose_context_in_response(expose);
            let app = Router::new()
                .route("/test", get(|| async { "完成" }))
                .with_request_logging_config(config);
            let response = app
                .oneshot(Request::get("/test").body(Body::empty()).unwrap())
                .await
                .unwrap();

            assert_eq!(
                response.extensions().get::<RequestLogContext>().is_some(),
                expected
            );
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn slow_queries_can_be_logged_independently_from_quiet_queries() {
        async fn run(log_slow: bool) -> String {
            let writer = SharedWriter::default();
            let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
            let config = RequestLoggingConfig::new()
                .quiet_queries(true)
                .log_slow_queries(log_slow)
                .slow_request_threshold(Duration::ZERO);
            let app = Router::new()
                .route("/query", get(|| async { "完成" }))
                .with_request_logging_config(config);
            app.oneshot(Request::get("/query").body(Body::empty()).unwrap())
                .await
                .unwrap();
            writer.output()
        }

        assert!(run(false).await.is_empty());
        assert_eq!(run(true).await.lines().count(), 1);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn subscriber_level_filter_skips_disabled_success_event() {
        async fn error_handler() -> Result<&'static str, crate::web::response::ApiError> {
            Err(crate::web::response::ApiError::err_bad_request("请求错误"))
        }

        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::WARN);

        let app = Router::new()
            .route("/success", get(|| async { "完成" }))
            .route("/error", get(error_handler))
            .with_request_logging();
        for uri in ["/success", "/error"] {
            let response = app
                .clone()
                .oneshot(Request::get(uri).body(Body::empty()).unwrap())
                .await
                .unwrap();
            assert_eq!(response.status(), StatusCode::OK);
        }

        let output = writer.output();
        assert_eq!(output.lines().count(), 1);
        assert!(output.contains(r#""level":"WARN""#));
        assert!(output.contains(r#""path":"/error""#));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn request_headers_are_not_recorded_by_default() {
        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);

        let app = Router::new()
            .route("/test", get(|| async { "完成" }))
            .with_request_logging();
        let response = app
            .oneshot(
                Request::get("/test")
                    // User-Agent 是协议标识,测试中保持稳定的 ASCII 值。
                    .header(USER_AGENT, "loveyu-kit-test-client")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let output = writer.output();
        assert!(!output.contains("loveyu-kit-test-client"));
        assert!(!output.contains(r#""headers""#));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn configured_request_headers_are_recorded() {
        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);

        let config = RequestLoggingConfig::new().include_headers([USER_AGENT, CONTENT_TYPE]);
        let app = Router::new()
            .route("/test", get(|| async { "完成" }))
            .with_request_logging_config(config);
        let response = app
            .oneshot(
                Request::get("/test")
                    // User-Agent 是协议标识,测试中保持稳定的 ASCII 值。
                    .header(USER_AGENT, "loveyu-kit-test-client")
                    .header(CONTENT_TYPE, "application/json")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let output = writer.output();
        let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        assert_eq!(
            log["fields"]["headers"]["user-agent"],
            "loveyu-kit-test-client"
        );
        assert_eq!(log["fields"]["headers"]["content-type"], "application/json");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn query_string_is_recorded_only_when_enabled() {
        async fn request(include_query: bool) -> String {
            let writer = SharedWriter::default();
            let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);

            let config = RequestLoggingConfig::new().include_query(include_query);
            let app = Router::new()
                .route("/test", get(|| async { "完成" }))
                .with_request_logging_config(config);
            let response = app
                .oneshot(
                    Request::get("/test?debug=loveyu-kit-query")
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();

            assert_eq!(response.status(), StatusCode::OK);
            writer.output()
        }

        assert!(!request(false).await.contains("loveyu-kit-query"));
        assert!(request(true).await.contains("loveyu-kit-query"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn skipped_success_paths_and_prefixes_do_not_emit_logs() {
        async fn handler() -> &'static str {
            "完成"
        }

        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);

        let config = RequestLoggingConfig::new()
            .skip_success_path("/health")
            .skip_success_path("/users/{id}")
            .skip_success_prefix("/static/");
        let app = Router::new()
            .route("/health", get(handler))
            .route("/users/{id}", get(handler))
            .route("/static/app.js", get(handler))
            .route("/normal", get(handler))
            .with_request_logging_config(config);

        for uri in ["/health", "/users/1", "/static/app.js", "/normal"] {
            let response = app
                .clone()
                .oneshot(Request::get(uri).body(Body::empty()).unwrap())
                .await
                .unwrap();
            assert_eq!(response.status(), StatusCode::OK);
        }

        let output = writer.output();
        assert_eq!(output.lines().count(), 1);
        assert!(output.contains(r#""path":"/normal""#));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn zero_success_sample_rate_skips_success_log() {
        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);

        let config = RequestLoggingConfig::new().success_sample_rate(0.0);
        let app = Router::new()
            .route("/test", get(|| async { "完成" }))
            .with_request_logging_config(config);
        let response = app
            .oneshot(Request::get("/test").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert!(writer.output().is_empty());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn slow_request_overrides_success_path_filter() {
        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);

        let config = RequestLoggingConfig::new()
            .skip_success_path("/health")
            .slow_request_threshold(Duration::ZERO);
        let app = Router::new()
            .route("/health", get(|| async { "正常" }))
            .with_request_logging_config(config);
        let response = app
            .oneshot(Request::get("/health").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let output = writer.output();
        assert_eq!(output.lines().count(), 1);
        assert!(output.contains(r#""level":"WARN""#));
        assert!(output.contains(r#""slow_request":true"#));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn errors_are_logged_even_when_success_logs_are_disabled() {
        async fn handler() -> Result<&'static str, crate::web::response::ApiError> {
            Err(crate::web::response::ApiError::err_not_found("数据不存在"))
        }

        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);

        let config = RequestLoggingConfig::new()
            .skip_success_path("/error")
            .success_sample_rate(0.0)
            .always_log_errors(true);
        let app = Router::new()
            .route("/error", get(handler))
            .with_request_logging_config(config);
        let response = app
            .oneshot(Request::get("/error").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let output = writer.output();
        assert_eq!(output.lines().count(), 1);
        assert!(output.contains(r#""error":{"code":404000"#));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn errors_can_follow_filter_and_sampling_rules() {
        async fn handler() -> Result<&'static str, crate::web::response::ApiError> {
            Err(crate::web::response::ApiError::err_not_found("数据不存在"))
        }

        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);

        let config = RequestLoggingConfig::new()
            .skip_success_path("/error")
            .success_sample_rate(0.0)
            .always_log_errors(false);
        let app = Router::new()
            .route("/error", get(handler))
            .with_request_logging_config(config);
        let response = app
            .oneshot(Request::get("/error").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert!(writer.output().is_empty());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn panic_returns_safe_response_and_logs_real_error_once() {
        async fn handler(Extension(context): Extension<RequestLogContext>) -> &'static str {
            context.insert("operation", "panic 前的业务操作");
            panic!("测试 panic 详情");
        }

        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);

        let app = Router::new()
            .route("/panic", get(handler))
            .with_request_logging();
        let response = app
            .oneshot(Request::get("/panic").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(value["code"], 500_000);
        assert_eq!(value["msg"], "系统内部错误");
        assert!(!String::from_utf8_lossy(&body).contains("测试 panic 详情"));

        let output = writer.output();
        assert_eq!(output.lines().count(), 1);
        let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        assert_eq!(log["level"], "ERROR");
        assert_eq!(log["fields"]["error"]["internal_error"], "测试 panic 详情");
        assert_eq!(log["fields"]["error"]["context"]["error_type"], "panic");
        assert_eq!(
            log["fields"]["request_context"]["operation"],
            "panic 前的业务操作"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn system_error_logs_internal_details_without_exposing_them() {
        async fn handler() -> Result<&'static str, crate::web::response::ApiError> {
            Err(crate::web::response::ApiError::err_database("查询失败")
                .with_error("数据库连接被拒绝")
                .with_context("operation", "查询用户"))
        }

        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);

        let app = Router::new()
            .route("/error", get(handler))
            .with_request_logging();
        let response = app
            .oneshot(Request::get("/error").body(Body::empty()).unwrap())
            .await
            .unwrap();
        let body = response.into_body().collect().await.unwrap().to_bytes();

        assert!(!String::from_utf8_lossy(&body).contains("数据库连接被拒绝"));
        let output = writer.output();
        assert_eq!(output.lines().count(), 1);
        let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        assert_eq!(log["level"], "ERROR");
        assert_eq!(log["fields"]["error"]["internal_error"], "数据库连接被拒绝");
        assert_eq!(log["fields"]["error"]["context"]["operation"], "查询用户");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn diagnostic_context_is_logged_without_internal_error() {
        async fn handler() -> Result<&'static str, crate::web::response::ApiError> {
            Err(crate::web::response::ApiError::err_bad_request("请求错误")
                .with_context("operation", "解析请求"))
        }

        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);

        let app = Router::new()
            .route("/error", get(handler))
            .with_request_logging();
        let response = app
            .oneshot(Request::get("/error").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let output = writer.output();
        assert_eq!(output.lines().count(), 1);
        let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        assert_eq!(log["level"], "WARN");
        assert_eq!(log["fields"]["error"]["context"]["operation"], "解析请求");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn trusted_subject_and_request_id_are_propagated_generically() {
        async fn handler(subject: TrustedSubject, request_id: RequestId) -> String {
            format!("{}:{request_id}", subject.id())
        }

        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
        let subject_header = HeaderName::from_static("x-gateway-subject");
        let config = RequestLoggingConfig::new()
            .trusted_subject_header(subject_header.clone())
            .trusted_subject_kind("user");
        let app = Router::new()
            .route("/profile", get(handler))
            .with_request_logging_config(config);
        let response = app
            .oneshot(
                Request::get("/profile")
                    .header(subject_header, "guid-1001")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let log: serde_json::Value = serde_json::from_str(writer.output().trim()).unwrap();
        assert_eq!(
            log["fields"]["request_context"]["subject"]["id"],
            "guid-1001"
        );
        assert_eq!(log["fields"]["request_context"]["subject"]["kind"], "user");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn quiet_queries_and_always_logged_commands_are_configurable() {
        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
        let config = RequestLoggingConfig::new()
            .quiet_queries(true)
            .always_log_commands(true)
            .success_sample_rate(0.0);
        let app = Router::new()
            .route("/query", get(|| async { "查询完成" }))
            .route("/command", post(|| async { "修改完成" }))
            .with_request_logging_config(config);

        for request in [
            Request::get("/query").body(Body::empty()).unwrap(),
            Request::post("/command").body(Body::empty()).unwrap(),
        ] {
            assert_eq!(
                app.clone().oneshot(request).await.unwrap().status(),
                StatusCode::OK
            );
        }

        let output = writer.output();
        assert_eq!(output.lines().count(), 1);
        let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        assert_eq!(log["fields"]["path"], "/command");
        assert_eq!(log["fields"]["operation_kind"], "command");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn sql_failure_is_aggregated_into_the_single_request_json() {
        use std::{error::Error, fmt};

        use crate::observability::{ResultApiErrorExt, SqlDiagnostic, SqlOperation};

        #[derive(Debug)]
        struct DatabaseError;

        impl fmt::Display for DatabaseError {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("唯一索引冲突")
            }
        }

        impl Error for DatabaseError {}

        async fn handler() -> Result<&'static str, crate::web::response::ApiError> {
            let result: Result<(), DatabaseError> = Err(DatabaseError);
            result.map_sql_error(
                crate::web::response::ApiError::err_database("保存失败,请稍后重试"),
                |source| {
                    SqlDiagnostic::new(
                        "create_user",
                        SqlOperation::Insert,
                        "INSERT INTO users(email) VALUES (?)",
                        source,
                    )
                    .with_safe_parameter("user_guid", "guid-1001")
                    .with_error_code("1062")
                    .with_constraint("uk_users_email")
                },
            )?;
            Ok("不会执行")
        }

        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
        let app = Router::new()
            .route("/users", post(handler))
            .with_request_logging();
        let response = app
            .oneshot(Request::post("/users").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        assert!(!String::from_utf8_lossy(&body).contains("唯一索引冲突"));
        assert!(!String::from_utf8_lossy(&body).contains("uk_users_email"));
        let output = writer.output();
        assert_eq!(output.lines().count(), 1);
        let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        let diagnostic = &log["fields"]["error"]["diagnostics"][0];
        assert_eq!(diagnostic["kind"], "sql");
        assert_eq!(diagnostic["name"], "create_user");
        assert_eq!(diagnostic["error"], "唯一索引冲突");
        assert_eq!(diagnostic["details"]["operation"], "insert");
        assert_eq!(diagnostic["details"]["error_code"], "1062");
        assert_eq!(
            diagnostic["details"]["safe_parameters"]["user_guid"],
            "guid-1001"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn recovered_sql_failure_is_not_hidden_by_quiet_query_policy() {
        use crate::observability::{SqlDiagnostic, SqlOperation};

        async fn handler() -> &'static str {
            RequestLogContext::with_current(|context| {
                context.record_sql_error(SqlDiagnostic::new(
                    "load_settings",
                    SqlOperation::Select,
                    "SELECT value FROM settings WHERE name = ?",
                    "数据库连接超时",
                ));
            });
            "使用默认配置"
        }

        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
        let config = RequestLoggingConfig::new()
            .quiet_queries(true)
            .success_sample_rate(0.0);
        let app = Router::new()
            .route("/settings", get(handler))
            .with_request_logging_config(config);
        let response = app
            .oneshot(Request::get("/settings").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let output = writer.output();
        assert_eq!(output.lines().count(), 1);
        let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        assert_eq!(log["level"], "ERROR");
        assert_eq!(log["fields"]["outcome"], "failure");
        assert_eq!(
            log["fields"]["request_context"]["diagnostics"][0]["name"],
            "load_settings"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn sensitive_headers_remain_redacted_when_included() {
        use axum::http::header::AUTHORIZATION;

        let writer = SharedWriter::default();
        let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
        let config = RequestLoggingConfig::new().include_header(AUTHORIZATION);
        let app = Router::new()
            .route("/test", get(|| async { "完成" }))
            .with_request_logging_config(config);
        let response = app
            .oneshot(
                Request::get("/test")
                    .header(AUTHORIZATION, "Bearer secret-token")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let output = writer.output();
        assert!(!output.contains("secret-token"));
        let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
        assert_eq!(log["fields"]["headers"]["authorization"], "[已脱敏]");
    }
}