mirror of
https://github.com/gabime/spdlog.git
synced 2025-09-29 01:29:35 +08:00
Compare commits
555 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
22a169bc31 | ||
![]() |
ac19803d03 | ||
![]() |
95485ee89b | ||
![]() |
bc61f69058 | ||
![]() |
0b86d6a451 | ||
![]() |
0317731dc9 | ||
![]() |
3dedb52163 | ||
![]() |
ad393b83a2 | ||
![]() |
01dac453db | ||
![]() |
03abdf49a0 | ||
![]() |
83b9149930 | ||
![]() |
5ca5cbd447 | ||
![]() |
597e89efe3 | ||
![]() |
683e44f5f8 | ||
![]() |
0b36d4e360 | ||
![]() |
67606e2460 | ||
![]() |
b6c6b30c0d | ||
![]() |
e5935f0ced | ||
![]() |
75c15e8028 | ||
![]() |
4831ae17d9 | ||
![]() |
22655d7554 | ||
![]() |
ff0e430e46 | ||
![]() |
e86dc8c338 | ||
![]() |
0814de6371 | ||
![]() |
34bc6907d0 | ||
![]() |
a6dd1a2b4b | ||
![]() |
4fe5d3d5e3 | ||
![]() |
937fe7e909 | ||
![]() |
89ab1e679d | ||
![]() |
559984b2fe | ||
![]() |
3ac9540351 | ||
![]() |
d5709c9d70 | ||
![]() |
891cc95add | ||
![]() |
0246b5657a | ||
![]() |
26ca1fb9f3 | ||
![]() |
6b4355b76f | ||
![]() |
90bd9692f5 | ||
![]() |
8878185628 | ||
![]() |
15066d1d37 | ||
![]() |
abaae6e28b | ||
![]() |
2170de8819 | ||
![]() |
300ec667f6 | ||
![]() |
348c4380d6 | ||
![]() |
98388d18de | ||
![]() |
bbc5753b96 | ||
![]() |
564eecaa3b | ||
![]() |
0480920058 | ||
![]() |
d977dd4395 | ||
![]() |
ca402379a9 | ||
![]() |
903bf2135d | ||
![]() |
1f732585b2 | ||
![]() |
224de0601e | ||
![]() |
9b84337830 | ||
![]() |
a4665c27df | ||
![]() |
3337015346 | ||
![]() |
42c466296a | ||
![]() |
a9fcf9db47 | ||
![]() |
f3b55fcab0 | ||
![]() |
b56b6509b1 | ||
![]() |
ac85e383a9 | ||
![]() |
2b326e90b8 | ||
![]() |
3e8be645d2 | ||
![]() |
81444265f4 | ||
![]() |
5716ab70ec | ||
![]() |
faaef7686d | ||
![]() |
9e6f5b6b2d | ||
![]() |
d28465bf60 | ||
![]() |
867fec260b | ||
![]() |
f5309d902a | ||
![]() |
82823e50dd | ||
![]() |
394f79e9d3 | ||
![]() |
595bbbd3e4 | ||
![]() |
2127572c33 | ||
![]() |
7d6c927684 | ||
![]() |
9d2d4c82df | ||
![]() |
515ce9bebb | ||
![]() |
7698bb0ae1 | ||
![]() |
c89a5148b2 | ||
![]() |
c37adba77b | ||
![]() |
95cc3dec3f | ||
![]() |
42c4a91041 | ||
![]() |
d253dad2ee | ||
![]() |
7f0265e674 | ||
![]() |
b9726ba66d | ||
![]() |
b20ffa7369 | ||
![]() |
854abdf5e6 | ||
![]() |
d0fc8a572c | ||
![]() |
8bc1ca0e44 | ||
![]() |
d38bd138cd | ||
![]() |
7766bc25d1 | ||
![]() |
34244656a6 | ||
![]() |
619849c793 | ||
![]() |
927b2b3942 | ||
![]() |
76389e057f | ||
![]() |
0a14e491ab | ||
![]() |
1f7f1c1ffb | ||
![]() |
6440733002 | ||
![]() |
02802af97f | ||
![]() |
a8169a3d6b | ||
![]() |
9ba7fc94a5 | ||
![]() |
48b71a02d7 | ||
![]() |
18ed04b990 | ||
![]() |
d09e03606c | ||
![]() |
b2017f5653 | ||
![]() |
c16eb80d7f | ||
![]() |
0c56f98a92 | ||
![]() |
490940cd53 | ||
![]() |
92d27b0aa3 | ||
![]() |
ca9c83f824 | ||
![]() |
fc900e2432 | ||
![]() |
e3257e56ab | ||
![]() |
7d2337c6eb | ||
![]() |
58629f1fea | ||
![]() |
132ec0a5fc | ||
![]() |
c2b47430fb | ||
![]() |
7906592230 | ||
![]() |
f57378d8ba | ||
![]() |
1ccdc225af | ||
![]() |
3e4df86ac0 | ||
![]() |
7054cf7a35 | ||
![]() |
2a7fc9e30e | ||
![]() |
f1b4f15dbb | ||
![]() |
c98152e9d0 | ||
![]() |
7c34859e0c | ||
![]() |
dd38e096b2 | ||
![]() |
ea89efbed7 | ||
![]() |
61408a0f29 | ||
![]() |
cca004efe4 | ||
![]() |
da3f3da92c | ||
![]() |
f0c35819bd | ||
![]() |
ff616002cf | ||
![]() |
e1c79869b6 | ||
![]() |
bd43403f5a | ||
![]() |
d3997cc4d1 | ||
![]() |
5b0b8579b2 | ||
![]() |
c927de137c | ||
![]() |
eb23d505f8 | ||
![]() |
2400cf16a4 | ||
![]() |
bbe3ace533 | ||
![]() |
3b87eb3d08 | ||
![]() |
d43a17304e | ||
![]() |
21d41b8e81 | ||
![]() |
332eaaf916 | ||
![]() |
0a5ada6411 | ||
![]() |
963f8d3485 | ||
![]() |
60a8c5f1c9 | ||
![]() |
d1a1024465 | ||
![]() |
0d7ff9ac47 | ||
![]() |
752d5685dc | ||
![]() |
c6c517431f | ||
![]() |
ee54f54ced | ||
![]() |
2c5c96e159 | ||
![]() |
a10763138e | ||
![]() |
208eb0ca07 | ||
![]() |
f0403fa9e4 | ||
![]() |
3f86b250e6 | ||
![]() |
d1819f5f76 | ||
![]() |
19c7e63858 | ||
![]() |
7efdcc26fe | ||
![]() |
3ab3970dd2 | ||
![]() |
5ab487dbae | ||
![]() |
55fbc2c78e | ||
![]() |
643426e2b2 | ||
![]() |
f31a834613 | ||
![]() |
683080be53 | ||
![]() |
d14b8a9ad6 | ||
![]() |
0f87ba6c93 | ||
![]() |
02bfa0898c | ||
![]() |
f5313f92f1 | ||
![]() |
e41a258b93 | ||
![]() |
ffa85cda1a | ||
![]() |
0123d41647 | ||
![]() |
2b0481deed | ||
![]() |
1389f86675 | ||
![]() |
cf6bb88af2 | ||
![]() |
8e19a267bd | ||
![]() |
3b55709e7f | ||
![]() |
f78bca4ad8 | ||
![]() |
713feca582 | ||
![]() |
26c20ed91d | ||
![]() |
e399249f31 | ||
![]() |
b4a1b4b59a | ||
![]() |
b309a88bea | ||
![]() |
e88bee49a6 | ||
![]() |
ec12770693 | ||
![]() |
5b3a18319e | ||
![]() |
3b73278348 | ||
![]() |
0ca2cb625e | ||
![]() |
67561f97ec | ||
![]() |
b667bae65d | ||
![]() |
54be9bd8b9 | ||
![]() |
06d0299639 | ||
![]() |
84851e230f | ||
![]() |
52aed9e0de | ||
![]() |
ead9a550fd | ||
![]() |
cf80b492a3 | ||
![]() |
69f3d2678e | ||
![]() |
8038bc2fc8 | ||
![]() |
f20b12cf3f | ||
![]() |
c8bd53509c | ||
![]() |
006124d816 | ||
![]() |
efd73ac956 | ||
![]() |
b7d7334451 | ||
![]() |
8284865f9a | ||
![]() |
1f8b04cbd1 | ||
![]() |
b3402a0b9f | ||
![]() |
4037959945 | ||
![]() |
d7313a3274 | ||
![]() |
8302086942 | ||
![]() |
6095db951b | ||
![]() |
817d2764b6 | ||
![]() |
62189602cb | ||
![]() |
0120dcc787 | ||
![]() |
6bfc0ec3a7 | ||
![]() |
f999d879d5 | ||
![]() |
c861e2d9cf | ||
![]() |
e696978d11 | ||
![]() |
fbf2e942a9 | ||
![]() |
d18f282938 | ||
![]() |
c10be7eaec | ||
![]() |
05ecad4263 | ||
![]() |
4cdb159ccb | ||
![]() |
fccb25586f | ||
![]() |
ab2f3307eb | ||
![]() |
db26a103d6 | ||
![]() |
32902f79ad | ||
![]() |
fab33dd230 | ||
![]() |
daaa025356 | ||
![]() |
ffe272c165 | ||
![]() |
6e763d2776 | ||
![]() |
c71b433a35 | ||
![]() |
0b91d55269 | ||
![]() |
9f41903067 | ||
![]() |
64de8807e2 | ||
![]() |
3848cbe24a | ||
![]() |
15ac7b08f7 | ||
![]() |
e47ecc1828 | ||
![]() |
c09641cf47 | ||
![]() |
92467db591 | ||
![]() |
ea5e7182ab | ||
![]() |
d38d53d9dd | ||
![]() |
c9e094d9fc | ||
![]() |
af75985ec6 | ||
![]() |
4b7c05903b | ||
![]() |
695912c7cf | ||
![]() |
5c06306ccc | ||
![]() |
d4fd17f64f | ||
![]() |
76d94e69ae | ||
![]() |
0f42744f5c | ||
![]() |
e8daf7c73b | ||
![]() |
0cf1af5bbf | ||
![]() |
a343328a21 | ||
![]() |
53a56b82af | ||
![]() |
64dd4dc219 | ||
![]() |
9e9da42c64 | ||
![]() |
5c410f4ca2 | ||
![]() |
0778211116 | ||
![]() |
574563d711 | ||
![]() |
e9d0b424d5 | ||
![]() |
eef981e05f | ||
![]() |
9f24f4bc69 | ||
![]() |
5da9818676 | ||
![]() |
ff59b07986 | ||
![]() |
1b6d4fd277 | ||
![]() |
7b19890deb | ||
![]() |
5370443ece | ||
![]() |
ad4fb1cf84 | ||
![]() |
7f8169f0da | ||
![]() |
66e8652862 | ||
![]() |
05cbdbc1ef | ||
![]() |
38584a1fca | ||
![]() |
d96d8c49ac | ||
![]() |
4bb623a0a3 | ||
![]() |
3aa94a0997 | ||
![]() |
ccad4ae04f | ||
![]() |
346b9ae5a1 | ||
![]() |
12f36debae | ||
![]() |
87acec6a91 | ||
![]() |
58a5e654f9 | ||
![]() |
e278953191 | ||
![]() |
573ddf8aec | ||
![]() |
4f32243214 | ||
![]() |
601bdfb1b4 | ||
![]() |
90454a93b2 | ||
![]() |
640921cd3f | ||
![]() |
fccee959b1 | ||
![]() |
67a8ecf2bf | ||
![]() |
d8701890b2 | ||
![]() |
2435f46d06 | ||
![]() |
4bece787c8 | ||
![]() |
d4ce938679 | ||
![]() |
033fe9f133 | ||
![]() |
25b10dc264 | ||
![]() |
a9c3630d1b | ||
![]() |
f3d99f41d4 | ||
![]() |
fdb46b857f | ||
![]() |
8d06df9775 | ||
![]() |
a8d6e60ec6 | ||
![]() |
4e643fa42c | ||
![]() |
eb234bbf91 | ||
![]() |
db1a221427 | ||
![]() |
5378f35239 | ||
![]() |
622f5eb967 | ||
![]() |
966d827d35 | ||
![]() |
bed56d3e52 | ||
![]() |
24173d5ebc | ||
![]() |
60853b5e54 | ||
![]() |
da2ff552c5 | ||
![]() |
742df52236 | ||
![]() |
1b4621962f | ||
![]() |
0a36828ff3 | ||
![]() |
85ea4297b9 | ||
![]() |
34cc3419fa | ||
![]() |
46fcd2e844 | ||
![]() |
23f0cdf901 | ||
![]() |
26bdf66659 | ||
![]() |
cf6f1dd01e | ||
![]() |
286eb59081 | ||
![]() |
40bb28e9b6 | ||
![]() |
aac085a9be | ||
![]() |
58e68901c7 | ||
![]() |
8e69c6e492 | ||
![]() |
4d98a14cb1 | ||
![]() |
5bf99dfd61 | ||
![]() |
bc42415ceb | ||
![]() |
284e6a80ac | ||
![]() |
0243882238 | ||
![]() |
877eee408e | ||
![]() |
8dd54de326 | ||
![]() |
09d729bfba | ||
![]() |
9caaca742e | ||
![]() |
ac95c3ffbf | ||
![]() |
9715d80030 | ||
![]() |
a0a1e5c078 | ||
![]() |
d7ba1fdd3d | ||
![]() |
2544fca519 | ||
![]() |
0b55e2c332 | ||
![]() |
b105046202 | ||
![]() |
de20255c71 | ||
![]() |
1a1c37db7c | ||
![]() |
a87700a28c | ||
![]() |
1f8e9ad0fc | ||
![]() |
e13e978af4 | ||
![]() |
28e334c728 | ||
![]() |
15a9427112 | ||
![]() |
010b0e1d75 | ||
![]() |
cd5ddca00d | ||
![]() |
f18e1fccfd | ||
![]() |
773b8c5a54 | ||
![]() |
fc3d18ed64 | ||
![]() |
68ed281461 | ||
![]() |
65ada37399 | ||
![]() |
9f539d7028 | ||
![]() |
c73a5ff918 | ||
![]() |
9858d4e918 | ||
![]() |
0dfb1d264e | ||
![]() |
a056b9115b | ||
![]() |
62ecc04212 | ||
![]() |
4a0f4fc186 | ||
![]() |
3a61dcd360 | ||
![]() |
04d0240f8d | ||
![]() |
13ebfc0779 | ||
![]() |
d70d5aa9d8 | ||
![]() |
70d3c2cd3e | ||
![]() |
6fbe0dec2c | ||
![]() |
9d3591dcd5 | ||
![]() |
8992f36fbf | ||
![]() |
3d203aa7c4 | ||
![]() |
cd8d7e6de9 | ||
![]() |
5d4e6f17ee | ||
![]() |
49f707ec93 | ||
![]() |
6a305df46d | ||
![]() |
35e9482574 | ||
![]() |
dac61d4e9c | ||
![]() |
d52e825bbc | ||
![]() |
4fa463dff6 | ||
![]() |
ebaa16f403 | ||
![]() |
175741ed1d | ||
![]() |
8d9d9899b7 | ||
![]() |
cff7448fb2 | ||
![]() |
0f8f510ebb | ||
![]() |
3812c22f86 | ||
![]() |
2b3000dddc | ||
![]() |
b278baf94e | ||
![]() |
4119b72d50 | ||
![]() |
da2c15ecb4 | ||
![]() |
25a702fc22 | ||
![]() |
ab178057db | ||
![]() |
c44cf5a720 | ||
![]() |
98ca01bf2d | ||
![]() |
d0ed873ab6 | ||
![]() |
0f24399887 | ||
![]() |
abbbda6f74 | ||
![]() |
1a5ee7ab83 | ||
![]() |
3a258ee5c9 | ||
![]() |
4d41fdf0fc | ||
![]() |
1586c4b0c7 | ||
![]() |
9198e97401 | ||
![]() |
346267c82f | ||
![]() |
529f72325f | ||
![]() |
1cf1209586 | ||
![]() |
36774529a4 | ||
![]() |
27dcb1008c | ||
![]() |
e8a9c7b13e | ||
![]() |
7be59851d5 | ||
![]() |
15cf9ec365 | ||
![]() |
c44c904161 | ||
![]() |
9e3d8d1650 | ||
![]() |
7b9668fe01 | ||
![]() |
2334c48e02 | ||
![]() |
afb949a417 | ||
![]() |
c9bb85c91d | ||
![]() |
13e1667d61 | ||
![]() |
3c106c9cec | ||
![]() |
1988668d10 | ||
![]() |
484d7f91e5 | ||
![]() |
53d58f222f | ||
![]() |
d5a72b1eaf | ||
![]() |
6b5ebab6ae | ||
![]() |
8107df08a8 | ||
![]() |
dc29500931 | ||
![]() |
31fc1aca53 | ||
![]() |
0db4b04ad3 | ||
![]() |
1aa9ea92e2 | ||
![]() |
2698f54a9c | ||
![]() |
6f977248bf | ||
![]() |
046fd62dc4 | ||
![]() |
da60dda2dd | ||
![]() |
d25fb08a75 | ||
![]() |
79e105243c | ||
![]() |
2d4e531ac9 | ||
![]() |
52403ad9ed | ||
![]() |
2d264855cc | ||
![]() |
c172c72be9 | ||
![]() |
79259fdb3f | ||
![]() |
cee35f7d24 | ||
![]() |
1f5f17622e | ||
![]() |
e8f7f80f2b | ||
![]() |
6db8beeade | ||
![]() |
4f66313440 | ||
![]() |
89b5bcfdc7 | ||
![]() |
26f706ebe3 | ||
![]() |
0cb38085a1 | ||
![]() |
cff6644b28 | ||
![]() |
63837530ed | ||
![]() |
62e09e73f7 | ||
![]() |
daef0a2374 | ||
![]() |
042045b998 | ||
![]() |
bad7284465 | ||
![]() |
6f0cb6365e | ||
![]() |
653ec05c0e | ||
![]() |
be2a751513 | ||
![]() |
840adfbbcf | ||
![]() |
acf32be842 | ||
![]() |
3999613eca | ||
![]() |
bff85725d2 | ||
![]() |
93008b2369 | ||
![]() |
be336e7514 | ||
![]() |
255f7f2dee | ||
![]() |
de2c07ac62 | ||
![]() |
844d54d7e6 | ||
![]() |
ff3e6c7248 | ||
![]() |
408a2229d6 | ||
![]() |
7cdd65075c | ||
![]() |
436ce16e79 | ||
![]() |
58320e2678 | ||
![]() |
a6f7edf94b | ||
![]() |
4a4f13be46 | ||
![]() |
a13b0abb7d | ||
![]() |
c081919320 | ||
![]() |
21f7f78130 | ||
![]() |
bb1b24c178 | ||
![]() |
3f30000088 | ||
![]() |
e6ce39f76e | ||
![]() |
10116b7717 | ||
![]() |
18edb8bd63 | ||
![]() |
dae1aeb1f7 | ||
![]() |
57085c892f | ||
![]() |
d67efb2cab | ||
![]() |
0e09ecbaa5 | ||
![]() |
e3699070a4 | ||
![]() |
bf40855825 | ||
![]() |
3ee4f2810d | ||
![]() |
79468cf676 | ||
![]() |
4037942a26 | ||
![]() |
cae6c9ab36 | ||
![]() |
15b393193a | ||
![]() |
53ab34928c | ||
![]() |
eb4a169cfb | ||
![]() |
6f6cadf31d | ||
![]() |
17513a6dce | ||
![]() |
a44560ddb6 | ||
![]() |
2b8afb38b7 | ||
![]() |
685ad74d53 | ||
![]() |
288ea11534 | ||
![]() |
b848ff8db9 | ||
![]() |
5881fcb0d6 | ||
![]() |
491a2e8732 | ||
![]() |
4a620a2c5e | ||
![]() |
05105155f8 | ||
![]() |
9f96545fa7 | ||
![]() |
0c60107e62 | ||
![]() |
49eb9cbdd8 | ||
![]() |
594d226056 | ||
![]() |
aac7dccf45 | ||
![]() |
c19e325b83 | ||
![]() |
bd92c23add | ||
![]() |
88335bd92e | ||
![]() |
a4602021d8 | ||
![]() |
dbe5c17a96 | ||
![]() |
c40555c0ac | ||
![]() |
bfc76278a9 | ||
![]() |
a1f283946e | ||
![]() |
066087b383 | ||
![]() |
e9d42e059f | ||
![]() |
d1dadc9814 | ||
![]() |
2cc620ef33 | ||
![]() |
cee705ccd3 | ||
![]() |
a8f72424db | ||
![]() |
31ed133932 | ||
![]() |
d3c6974e99 | ||
![]() |
1271081865 | ||
![]() |
8a638a95a0 | ||
![]() |
d9f726f2a5 | ||
![]() |
5f3521b3d4 | ||
![]() |
9a68bd8cc8 | ||
![]() |
9b7812a0f2 | ||
![]() |
4858d7e454 | ||
![]() |
fbb3f41dff | ||
![]() |
1472048b97 | ||
![]() |
4aad51a352 | ||
![]() |
9a0a0c2d8c | ||
![]() |
fcc809f4f1 | ||
![]() |
f3369677ef | ||
![]() |
a03f9eb156 | ||
![]() |
aa65dd8905 | ||
![]() |
856b4f4654 | ||
![]() |
9369fe8c27 | ||
![]() |
1549ff12f1 | ||
![]() |
70357ceff2 | ||
![]() |
cfe7cac1c4 | ||
![]() |
fb70eca0a3 | ||
![]() |
cf2bf488a2 | ||
![]() |
5c02fc47b9 | ||
![]() |
4021e5eea9 | ||
![]() |
5cd0b6272d | ||
![]() |
bf49bebe7a | ||
![]() |
1e8299e893 | ||
![]() |
5381061d97 | ||
![]() |
274558c430 | ||
![]() |
188afe20f9 | ||
![]() |
1add9c9a02 | ||
![]() |
e7d4b99350 | ||
![]() |
8627721533 | ||
![]() |
6696416107 |
@@ -1,6 +1,32 @@
|
||||
Checks: 'modernize-*,modernize-use-override,google-*,-google-runtime-references,misc-*,clang-analyzer-*,-misc-non-private-member-variables-in-classes'
|
||||
Checks: 'cppcoreguidelines-*,
|
||||
performance-*,
|
||||
modernize-*,
|
||||
google-*,
|
||||
misc-*,
|
||||
cert-*,
|
||||
readability-*,
|
||||
clang-analyzer-*,
|
||||
-performance-unnecessary-value-param,
|
||||
-modernize-use-trailing-return-type,
|
||||
-google-runtime-references,
|
||||
-misc-non-private-member-variables-in-classes,
|
||||
-readability-braces-around-statements,
|
||||
-google-readability-braces-around-statements,
|
||||
-cppcoreguidelines-avoid-magic-numbers,
|
||||
-readability-magic-numbers,
|
||||
-readability-magic-numbers,
|
||||
-cppcoreguidelines-pro-type-vararg,
|
||||
-cppcoreguidelines-pro-bounds-pointer-arithmetic,
|
||||
-cppcoreguidelines-avoid-c-arrays,
|
||||
-modernize-avoid-c-arrays,
|
||||
-cppcoreguidelines-pro-bounds-array-to-pointer-decay,
|
||||
-readability-named-parameter,
|
||||
-cert-env33-c
|
||||
'
|
||||
|
||||
|
||||
WarningsAsErrors: ''
|
||||
HeaderFilterRegex: 'async.h|async_logger.h|common.h|details|formatter.h|logger.h|sinks|spdlog.h|tweakme.h|version.h'
|
||||
HeaderFilterRegex: '*spdlog/[^f].*'
|
||||
AnalyzeTemporaryDtors: false
|
||||
FormatStyle: none
|
||||
|
37
.travis.yml
37
.travis.yml
@@ -30,15 +30,16 @@ addons: &clang35
|
||||
- ubuntu-toolchain-r-test
|
||||
- llvm-toolchain-precise-3.5
|
||||
|
||||
# Clang 7.0
|
||||
addons: &clang70
|
||||
|
||||
addons: &clang10
|
||||
apt:
|
||||
packages:
|
||||
- clang-7
|
||||
- clang-10
|
||||
- lldb-10
|
||||
- lld-10
|
||||
sources:
|
||||
- ubuntu-toolchain-r-test
|
||||
- llvm-toolchain-trusty-7
|
||||
|
||||
- sourceline: "deb http://apt.llvm.org/bionic/ llvm-toolchain-bionic-10 main"
|
||||
key_url: "https://apt.llvm.org/llvm-snapshot.gpg.key"
|
||||
|
||||
|
||||
matrix:
|
||||
@@ -65,17 +66,20 @@ matrix:
|
||||
os: linux
|
||||
addons: *clang35
|
||||
|
||||
# Test clang-7.0: C++11, Build=Debug, ASAN=On
|
||||
- env: CLANG_VERSION=7 BUILD_TYPE=Debug CPP=11 ASAN=On TSAN=Off
|
||||
dist: bionic
|
||||
|
||||
- env: CLANG_VERSION=7 BUILD_TYPE=Release CPP=11 ASAN=On TSAN=Off
|
||||
dist: bionic
|
||||
|
||||
# osx
|
||||
- env: BUILD_TYPE=Release CPP=11 ASAN=Off TSAN=Off
|
||||
os: osx
|
||||
|
||||
# Test clang-10.0: C++11, Build=Debug/Release
|
||||
- env: CLANG_VERSION=10 BUILD_TYPE=Debug CPP=11
|
||||
os: linux
|
||||
dist: bionic
|
||||
addons: *clang10
|
||||
|
||||
- env: CLANG_VERSION=10 BUILD_TYPE=Release CPP=11 ASAN=On
|
||||
os: linux
|
||||
dist: bionic
|
||||
addons: *clang10
|
||||
|
||||
|
||||
before_script:
|
||||
@@ -97,6 +101,7 @@ script:
|
||||
-DCMAKE_CXX_STANDARD=$CPP \
|
||||
-DSPDLOG_BUILD_EXAMPLE=ON \
|
||||
-DSPDLOG_BUILD_EXAMPLE_HO=ON \
|
||||
-DSPDLOG_ENABLE_WARNINGS=ON \
|
||||
-DSPDLOG_BUILD_BENCH=OFF \
|
||||
-DSPDLOG_BUILD_TESTS=ON \
|
||||
-DSPDLOG_BUILD_TESTS_HO=OFf \
|
||||
@@ -104,8 +109,4 @@ script:
|
||||
|
||||
- make VERBOSE=1 -j2
|
||||
- ctest -j2 --output-on-failure
|
||||
|
||||
|
||||
|
||||
notifications:
|
||||
email: false
|
||||
|
||||
|
307
CMakeLists.txt
307
CMakeLists.txt
@@ -1,57 +1,75 @@
|
||||
# Copyright(c) 2019 spdlog authors
|
||||
# Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
# Copyright(c) 2019 spdlog authors Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
cmake_minimum_required(VERSION 3.2)
|
||||
|
||||
#---------------------------------------------------------------------------------------
|
||||
if(${CMAKE_VERSION} VERSION_LESS 3.11)
|
||||
cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION})
|
||||
else()
|
||||
cmake_policy(VERSION 3.11)
|
||||
endif()
|
||||
|
||||
enable_language(C)
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Start spdlog project
|
||||
#---------------------------------------------------------------------------------------
|
||||
include(GNUInstallDirs)
|
||||
# ---------------------------------------------------------------------------------------
|
||||
include(cmake/utils.cmake)
|
||||
include(cmake/ide.cmake)
|
||||
|
||||
spdlog_extract_version()
|
||||
|
||||
#---------------------------------------------------------------------------------------
|
||||
project(spdlog VERSION ${SPDLOG_VERSION} LANGUAGES CXX)
|
||||
message(STATUS "Build spdlog: ${SPDLOG_VERSION}")
|
||||
|
||||
include(GNUInstallDirs)
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Set default build to release
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if(NOT CMAKE_BUILD_TYPE)
|
||||
set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose Release or Debug" FORCE)
|
||||
endif()
|
||||
|
||||
project(spdlog VERSION ${SPDLOG_VERSION} LANGUAGES CXX)
|
||||
message(STATUS "Build spdlog: ${SPDLOG_VERSION}")
|
||||
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Compiler config
|
||||
#---------------------------------------------------------------------------------------
|
||||
set(CMAKE_CXX_STANDARD 11)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if(NOT CMAKE_CXX_STANDARD)
|
||||
set(CMAKE_CXX_STANDARD 11)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
endif()
|
||||
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
#---------------------------------------------------------------------------------------
|
||||
if(CMAKE_SYSTEM_NAME MATCHES "CYGWIN")
|
||||
set(CMAKE_CXX_EXTENSIONS ON)
|
||||
endif()
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Set SPDLOG_MASTER_PROJECT to ON if we are building spdlog
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Check if spdlog is being used directly or via add_subdirectory, but allow overriding
|
||||
if (NOT DEFINED SPDLOG_MASTER_PROJECT)
|
||||
if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
|
||||
if(NOT DEFINED SPDLOG_MASTER_PROJECT)
|
||||
if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
|
||||
set(SPDLOG_MASTER_PROJECT ON)
|
||||
else()
|
||||
set(SPDLOG_MASTER_PROJECT OFF)
|
||||
endif()
|
||||
endif ()
|
||||
endif()
|
||||
|
||||
option(SPDLOG_BUILD_ALL "Build all artifacts" OFF)
|
||||
|
||||
# build shared option
|
||||
if(NOT WIN32)
|
||||
option(SPDLOG_BUILD_SHARED "Build shared library" OFF)
|
||||
endif()
|
||||
option(SPDLOG_BUILD_SHARED "Build shared library" OFF)
|
||||
|
||||
# precompiled headers option
|
||||
option(SPDLOG_ENABLE_PCH "Build static or shared library using precompiled header to speed up compilation time" OFF)
|
||||
|
||||
# example options
|
||||
option(SPDLOG_BUILD_EXAMPLE "Build example" ${SPDLOG_MASTER_PROJECT})
|
||||
option(SPDLOG_BUILD_EXAMPLE_HO "Build header only example" OFF)
|
||||
|
||||
# testing options
|
||||
option(SPDLOG_BUILD_TESTS "Build tests" ${SPDLOG_MASTER_PROJECT})
|
||||
option(SPDLOG_BUILD_TESTS "Build tests" OFF)
|
||||
option(SPDLOG_BUILD_TESTS_HO "Build tests using the header only version" OFF)
|
||||
|
||||
# bench options
|
||||
@@ -60,39 +78,73 @@ option(SPDLOG_BUILD_BENCH "Build benchmarks (Requires https://github.com/google/
|
||||
# sanitizer options
|
||||
option(SPDLOG_SANITIZE_ADDRESS "Enable address sanitizer in tests" OFF)
|
||||
|
||||
# warning options
|
||||
option(SPDLOG_BUILD_WARNINGS "Enable compiler warnings" OFF)
|
||||
|
||||
# install options
|
||||
option(SPDLOG_INSTALL "Generate the install target" ${SPDLOG_MASTER_PROJECT})
|
||||
option(SPDLOG_FMT_EXTERNAL "Use external fmt library instead of bundled" OFF)
|
||||
|
||||
if(WIN32)
|
||||
option(SPDLOG_WCHAR_SUPPORT "Support wchar api" OFF)
|
||||
endif()
|
||||
|
||||
option(SPDLOG_FMT_EXTERNAL_HO "Use external fmt header-only library instead of bundled" OFF)
|
||||
option(SPDLOG_NO_EXCEPTIONS "Compile with -fno-exceptions. Call abort() on any spdlog exceptions" OFF)
|
||||
|
||||
if(SPDLOG_FMT_EXTERNAL AND SPDLOG_FMT_EXTERNAL_HO)
|
||||
message(FATAL_ERROR "SPDLOG_FMT_EXTERNAL and SPDLOG_FMT_EXTERNAL_HO are mutually exclusive")
|
||||
endif()
|
||||
|
||||
# misc tweakme options
|
||||
if(WIN32)
|
||||
option(SPDLOG_WCHAR_SUPPORT "Support wchar api" OFF)
|
||||
option(SPDLOG_WCHAR_FILENAMES "Support wchar filenames" OFF)
|
||||
endif()
|
||||
if(${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
|
||||
option(SPDLOG_CLOCK_COARSE
|
||||
"Use the much faster (but much less accurate) CLOCK_REALTIME_COARSE instead of the regular clock," OFF)
|
||||
endif()
|
||||
|
||||
option(SPDLOG_PREVENT_CHILD_FD "Prevent from child processes to inherit log file descriptors" OFF)
|
||||
option(SPDLOG_NO_THREAD_ID "prevent spdlog from querying the thread id on each log call if thread id is not needed" OFF)
|
||||
option(SPDLOG_NO_TLS "prevent spdlog from using thread local storage" OFF)
|
||||
option(
|
||||
SPDLOG_NO_ATOMIC_LEVELS
|
||||
"prevent spdlog from using of std::atomic log levels (use only if your code never modifies log levels concurrently"
|
||||
OFF)
|
||||
|
||||
# clang-tidy
|
||||
if(${CMAKE_VERSION} VERSION_GREATER "3.5")
|
||||
option(SPDLOG_TIDY "run clang-tidy" OFF)
|
||||
endif()
|
||||
|
||||
if(SPDLOG_TIDY)
|
||||
set(CMAKE_CXX_CLANG_TIDY "clang-tidy")
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
message(STATUS "Enabled clang-tidy")
|
||||
endif()
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
message(STATUS "Build type: " ${CMAKE_BUILD_TYPE})
|
||||
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Static/Shared library (shared not supported in windows yet)
|
||||
#---------------------------------------------------------------------------------------
|
||||
set(SPDLOG_SRCS
|
||||
src/spdlog.cpp
|
||||
src/stdout_sinks.cpp
|
||||
src/fmt.cpp
|
||||
src/color_sinks.cpp
|
||||
src/file_sinks.cpp
|
||||
src/async.cpp)
|
||||
# ---------------------------------------------------------------------------------------
|
||||
set(SPDLOG_SRCS src/spdlog.cpp src/stdout_sinks.cpp src/color_sinks.cpp src/file_sinks.cpp src/async.cpp src/cfg.cpp)
|
||||
|
||||
set(SPDLOG_CFLAGS "${PROJECT_NAME}")
|
||||
if(NOT SPDLOG_FMT_EXTERNAL AND NOT SPDLOG_FMT_EXTERNAL_HO)
|
||||
list(APPEND SPDLOG_SRCS src/fmt.cpp)
|
||||
endif()
|
||||
|
||||
if (SPDLOG_BUILD_SHARED)
|
||||
if(WIN32)
|
||||
message(FATAL_ERROR "spdlog shared lib is not yet supported under windows")
|
||||
endif()
|
||||
if(WIN32 AND SPDLOG_BUILD_SHARED)
|
||||
list(APPEND SPDLOG_SRCS ${CMAKE_CURRENT_BINARY_DIR}/version.rc)
|
||||
endif()
|
||||
|
||||
if(SPDLOG_BUILD_SHARED)
|
||||
add_library(spdlog SHARED ${SPDLOG_SRCS} ${SPDLOG_ALL_HEADERS})
|
||||
target_compile_definitions(spdlog PUBLIC SPDLOG_SHARED_LIB)
|
||||
if(WIN32)
|
||||
target_compile_options(spdlog PUBLIC /wd4251 /wd4275)
|
||||
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/version.rc.in ${CMAKE_CURRENT_BINARY_DIR}/version.rc @ONLY)
|
||||
endif()
|
||||
if(NOT SPDLOG_FMT_EXTERNAL AND NOT SPDLOG_FMT_EXTERNAL_HO)
|
||||
target_compile_definitions(spdlog PRIVATE FMT_EXPORT PUBLIC FMT_SHARED)
|
||||
endif()
|
||||
else()
|
||||
add_library(spdlog STATIC ${SPDLOG_SRCS} ${SPDLOG_ALL_HEADERS})
|
||||
endif()
|
||||
@@ -100,124 +152,173 @@ endif()
|
||||
add_library(spdlog::spdlog ALIAS spdlog)
|
||||
|
||||
target_compile_definitions(spdlog PUBLIC SPDLOG_COMPILED_LIB)
|
||||
target_include_directories(spdlog PUBLIC
|
||||
"$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include>"
|
||||
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>")
|
||||
target_include_directories(spdlog PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include>"
|
||||
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>")
|
||||
target_link_libraries(spdlog PUBLIC Threads::Threads)
|
||||
spdlog_enable_warnings(spdlog)
|
||||
|
||||
set_target_properties(spdlog PROPERTIES VERSION ${SPDLOG_VERSION} SOVERSION ${SPDLOG_VERSION_MAJOR})
|
||||
set_target_properties(spdlog PROPERTIES DEBUG_POSTFIX d)
|
||||
|
||||
#---------------------------------------------------------------------------------------
|
||||
if(COMMAND target_precompile_headers AND SPDLOG_ENABLE_PCH)
|
||||
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/pch.h.in ${PROJECT_BINARY_DIR}/spdlog_pch.h @ONLY)
|
||||
target_precompile_headers(spdlog PRIVATE ${PROJECT_BINARY_DIR}/spdlog_pch.h)
|
||||
endif()
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Header only version
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
add_library(spdlog_header_only INTERFACE)
|
||||
add_library(spdlog::spdlog_header_only ALIAS spdlog_header_only)
|
||||
|
||||
target_include_directories(spdlog_header_only INTERFACE
|
||||
"$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include>"
|
||||
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>")
|
||||
target_include_directories(spdlog_header_only INTERFACE "$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include>"
|
||||
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>")
|
||||
target_link_libraries(spdlog_header_only INTERFACE Threads::Threads)
|
||||
|
||||
|
||||
#---------------------------------------------------------------------------------------
|
||||
# Use fmt package if using exertnal fmt
|
||||
#---------------------------------------------------------------------------------------
|
||||
if(SPDLOG_FMT_EXTERNAL)
|
||||
if (NOT TARGET fmt::fmt)
|
||||
find_package(fmt REQUIRED)
|
||||
endif ()
|
||||
|
||||
set(SPDLOG_CFLAGS "${SPDLOG_CFLAGS} -DSPDLOG_FMT_EXTERNAL")
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Use fmt package if using external fmt
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if(SPDLOG_FMT_EXTERNAL OR SPDLOG_FMT_EXTERNAL_HO)
|
||||
if(NOT TARGET fmt::fmt)
|
||||
find_package(fmt 5.3.0 REQUIRED)
|
||||
endif()
|
||||
target_compile_definitions(spdlog PUBLIC SPDLOG_FMT_EXTERNAL)
|
||||
target_link_libraries(spdlog PUBLIC fmt::fmt)
|
||||
|
||||
target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_FMT_EXTERNAL)
|
||||
target_link_libraries(spdlog_header_only INTERFACE fmt::fmt)
|
||||
|
||||
# use external fmt-header-nly
|
||||
if(SPDLOG_FMT_EXTERNAL_HO)
|
||||
target_link_libraries(spdlog PUBLIC fmt::fmt-header-only)
|
||||
target_link_libraries(spdlog_header_only INTERFACE fmt::fmt-header-only)
|
||||
else() # use external compile fmt
|
||||
target_link_libraries(spdlog PUBLIC fmt::fmt)
|
||||
target_link_libraries(spdlog_header_only INTERFACE fmt::fmt)
|
||||
endif()
|
||||
|
||||
set(PKG_CONFIG_REQUIRES fmt) # add dependency to pkg-config
|
||||
endif()
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Misc definitions according to tweak options
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if(SPDLOG_WCHAR_SUPPORT)
|
||||
target_compile_definitions(spdlog PUBLIC SPDLOG_WCHAR_TO_UTF8_SUPPORT)
|
||||
target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_WCHAR_TO_UTF8_SUPPORT)
|
||||
endif()
|
||||
target_compile_definitions(spdlog PUBLIC SPDLOG_WCHAR_TO_UTF8_SUPPORT)
|
||||
target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_WCHAR_TO_UTF8_SUPPORT)
|
||||
endif()
|
||||
|
||||
if(SPDLOG_NO_EXCEPTIONS)
|
||||
target_compile_definitions(spdlog PUBLIC SPDLOG_NO_EXCEPTIONS)
|
||||
if(SPDLOG_WCHAR_FILENAMES)
|
||||
target_compile_definitions(spdlog PUBLIC SPDLOG_WCHAR_FILENAMES)
|
||||
target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_WCHAR_FILENAMES)
|
||||
endif()
|
||||
|
||||
target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_NO_EXCEPTIONS)
|
||||
if(SPDLOG_NO_EXCEPTIONS)
|
||||
target_compile_definitions(spdlog PUBLIC SPDLOG_NO_EXCEPTIONS)
|
||||
|
||||
target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_NO_EXCEPTIONS)
|
||||
|
||||
if(NOT MSVC)
|
||||
target_compile_options(spdlog PRIVATE -fno-exceptions)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
|
||||
#---------------------------------------------------------------------------------------
|
||||
# Build binaries
|
||||
#---------------------------------------------------------------------------------------
|
||||
if(SPDLOG_BUILD_EXAMPLE OR SPDLOG_BUILD_EXAMPLE_HO)
|
||||
message(STATUS "Generating examples")
|
||||
add_subdirectory(example)
|
||||
if(SPDLOG_CLOCK_COARSE)
|
||||
target_compile_definitions(spdlog PRIVATE SPDLOG_CLOCK_COARSE)
|
||||
target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_CLOCK_COARSE)
|
||||
endif()
|
||||
|
||||
if(SPDLOG_BUILD_TESTS OR SPDLOG_BUILD_TESTS_HO)
|
||||
if(SPDLOG_PREVENT_CHILD_FD)
|
||||
target_compile_definitions(spdlog PRIVATE SPDLOG_PREVENT_CHILD_FD)
|
||||
target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_PREVENT_CHILD_FD)
|
||||
endif()
|
||||
|
||||
if(SPDLOG_NO_THREAD_ID)
|
||||
target_compile_definitions(spdlog PRIVATE SPDLOG_NO_THREAD_ID)
|
||||
target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_NO_THREAD_ID)
|
||||
endif()
|
||||
|
||||
if(SPDLOG_NO_TLS)
|
||||
target_compile_definitions(spdlog PRIVATE SPDLOG_NO_TLS)
|
||||
target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_NO_TLS)
|
||||
endif()
|
||||
|
||||
if(SPDLOG_NO_ATOMIC_LEVELS)
|
||||
target_compile_definitions(spdlog PUBLIC SPDLOG_NO_ATOMIC_LEVELS)
|
||||
target_compile_definitions(spdlog_header_only INTERFACE SPDLOG_NO_ATOMIC_LEVELS)
|
||||
endif()
|
||||
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Build binaries
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if(SPDLOG_BUILD_EXAMPLE OR SPDLOG_BUILD_EXAMPLE_HO OR SPDLOG_BUILD_ALL)
|
||||
message(STATUS "Generating example(s)")
|
||||
add_subdirectory(example)
|
||||
spdlog_enable_warnings(example)
|
||||
if(SPDLOG_BUILD_EXAMPLE_HO)
|
||||
spdlog_enable_warnings(example_header_only)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(SPDLOG_BUILD_TESTS OR SPDLOG_BUILD_TESTS_HO OR SPDLOG_BUILD_ALL)
|
||||
message(STATUS "Generating tests")
|
||||
enable_testing()
|
||||
add_subdirectory(tests)
|
||||
endif()
|
||||
|
||||
if(SPDLOG_BUILD_BENCH)
|
||||
if(SPDLOG_BUILD_BENCH OR SPDLOG_BUILD_ALL)
|
||||
message(STATUS "Generating benchmarks")
|
||||
add_subdirectory(bench)
|
||||
endif()
|
||||
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Install
|
||||
#---------------------------------------------------------------------------------------
|
||||
if (SPDLOG_INSTALL)
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if(SPDLOG_INSTALL)
|
||||
message(STATUS "Generating install")
|
||||
set(project_config_in "${CMAKE_CURRENT_LIST_DIR}/cmake/spdlogConfig.cmake.in")
|
||||
set(project_config_out "${CMAKE_CURRENT_BINARY_DIR}/spdlogConfig.cmake")
|
||||
set(config_targets_file "spdlogConfigTargets.cmake")
|
||||
set(version_config_file "${CMAKE_CURRENT_BINARY_DIR}/spdlogConfigVersion.cmake")
|
||||
set(export_dest_dir "${CMAKE_INSTALL_LIBDIR}/spdlog/cmake")
|
||||
set(export_dest_dir "${CMAKE_INSTALL_LIBDIR}/cmake/spdlog")
|
||||
set(pkgconfig_install_dir "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
|
||||
set(pkg_config "${CMAKE_BINARY_DIR}/${PROJECT_NAME}.pc")
|
||||
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Include files
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
install(DIRECTORY include/ DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" PATTERN "fmt/bundled" EXCLUDE)
|
||||
install(TARGETS spdlog spdlog_header_only EXPORT spdlog DESTINATION "${CMAKE_INSTALL_LIBDIR}/spdlog")
|
||||
install(
|
||||
TARGETS spdlog spdlog_header_only
|
||||
EXPORT spdlog
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
|
||||
|
||||
if(NOT SPDLOG_FMT_EXTERNAL)
|
||||
if(NOT SPDLOG_FMT_EXTERNAL AND NOT SPDLOG_FMT_EXTERNAL_HO)
|
||||
install(DIRECTORY include/${PROJECT_NAME}/fmt/bundled/
|
||||
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}/fmt/bundled/")
|
||||
endif()
|
||||
|
||||
#---------------------------------------------------------------------------------------
|
||||
# Package and version files
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Install pkg-config file
|
||||
# ---------------------------------------------------------------------------------------
|
||||
get_target_property(PKG_CONFIG_DEFINES spdlog INTERFACE_COMPILE_DEFINITIONS)
|
||||
string(REPLACE ";" " -D" PKG_CONFIG_DEFINES "${PKG_CONFIG_DEFINES}")
|
||||
string(CONCAT PKG_CONFIG_DEFINES "-D" "${PKG_CONFIG_DEFINES}")
|
||||
configure_file("cmake/${PROJECT_NAME}.pc.in" "${pkg_config}" @ONLY)
|
||||
install(FILES "${pkg_config}" DESTINATION "${pkgconfig_install_dir}")
|
||||
|
||||
install(EXPORT spdlog
|
||||
DESTINATION ${export_dest_dir}
|
||||
NAMESPACE spdlog::
|
||||
FILE ${config_targets_file})
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Install CMake config files
|
||||
# ---------------------------------------------------------------------------------------
|
||||
install(EXPORT spdlog DESTINATION ${export_dest_dir} NAMESPACE spdlog:: FILE ${config_targets_file})
|
||||
|
||||
include(CMakePackageConfigHelpers)
|
||||
configure_file("${project_config_in}" "${project_config_out}" @ONLY)
|
||||
|
||||
write_basic_package_version_file("${version_config_file}" COMPATIBILITY SameMajorVersion)
|
||||
install(FILES
|
||||
"${project_config_out}"
|
||||
"${version_config_file}" DESTINATION "${export_dest_dir}")
|
||||
install(FILES "${project_config_out}" "${version_config_file}" DESTINATION "${export_dest_dir}")
|
||||
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Support creation of installable packages
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
include(cmake/spdlogCPack.cmake)
|
||||
|
||||
endif ()
|
||||
endif()
|
||||
|
4
LICENSE
4
LICENSE
@@ -20,3 +20,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
-- NOTE: Third party dependency used by this software --
|
||||
This software depends on the fmt lib (MIT License),
|
||||
and users must comply to its license: https://github.com/fmtlib/fmt/blob/master/LICENSE.rst
|
||||
|
||||
|
107
README.md
107
README.md
@@ -1,14 +1,12 @@
|
||||
# spdlog
|
||||
|
||||
Very fast, header-only/compiled, C++ logging library. [](https://travis-ci.org/gabime/spdlog) [](https://ci.appveyor.com/project/gabime/spdlog)
|
||||
|
||||
|
||||
Very fast, header-only/compiled, C++ logging library. [](https://travis-ci.org/gabime/spdlog) [](https://ci.appveyor.com/project/gabime/spdlog) [](https://github.com/gabime/spdlog/releases/latest)
|
||||
|
||||
## Install
|
||||
#### Header only version
|
||||
Copy the source [folder](https://github.com/gabime/spdlog/tree/v1.x/include/spdlog) to your build tree and use a C++11 compiler.
|
||||
|
||||
#### Static lib version (recommended - much faster compile times, v1.4.0)
|
||||
#### Static lib version (recommended - much faster compile times)
|
||||
```console
|
||||
$ git clone https://github.com/gabime/spdlog.git
|
||||
$ cd spdlog && mkdir build && cd build
|
||||
@@ -25,18 +23,21 @@ $ cmake .. && make -j
|
||||
|
||||
## Package managers:
|
||||
* Homebrew: `brew install spdlog`
|
||||
* MacPorts: `sudo port install spdlog`
|
||||
* FreeBSD: `cd /usr/ports/devel/spdlog/ && make install clean`
|
||||
* Fedora: `yum install spdlog`
|
||||
* Gentoo: `emerge dev-libs/spdlog`
|
||||
* Arch Linux: `yaourt -S spdlog-git`
|
||||
* Arch Linux: `pacman -S spdlog`
|
||||
* vcpkg: `vcpkg install spdlog`
|
||||
* conan: `spdlog/[>=1.4.1]`
|
||||
* conda: `conda install -c conda-forge spdlog`
|
||||
|
||||
|
||||
## Features
|
||||
* Very fast (see [benchmarks](#benchmarks) below).
|
||||
* Headers only, just copy and use. Or use as a compiled library.
|
||||
* Headers only or compiled
|
||||
* Feature rich formatting, using the excellent [fmt](https://github.com/fmtlib/fmt) library.
|
||||
* **New!** [Backtrace](#backtrace-support) support - store debug or other messages in a ring buffer and display later on demand.
|
||||
* Fast asynchronous mode (optional)
|
||||
* Asynchronous mode (optional)
|
||||
* [Custom](https://github.com/gabime/spdlog/wiki/3.-Custom-formatting) formatting.
|
||||
* Multi/Single threaded loggers.
|
||||
* Various log targets:
|
||||
@@ -46,8 +47,9 @@ $ cmake .. && make -j
|
||||
* syslog.
|
||||
* Windows debugger (```OutputDebugString(..)```)
|
||||
* Easily extendable with custom log targets (just implement a single function in the [sink](include/spdlog/sinks/sink.h) interface).
|
||||
* Severity based filtering - threshold levels can be modified in runtime as well as in compile time.
|
||||
|
||||
* Log filtering - log levels can be modified in runtime as well as in compile time.
|
||||
* Support for loading log levels from argv or from environment var.
|
||||
* [Backtrace](#backtrace-support) support - store debug messages in a ring buffer and display later on demand.
|
||||
|
||||
## Usage samples
|
||||
|
||||
@@ -75,15 +77,17 @@ int main()
|
||||
|
||||
// Compile time log levels
|
||||
// define SPDLOG_ACTIVE_LEVEL to desired level
|
||||
SPDLOG_TRACE("Some trace message with param {}", {});
|
||||
SPDLOG_TRACE("Some trace message with param {}", 42);
|
||||
SPDLOG_DEBUG("Some debug message");
|
||||
|
||||
// Set the default logger to file logger
|
||||
auto file_logger = spdlog::basic_logger_mt("basic_logger", "logs/basic.txt");
|
||||
spdlog::set_default_logger(file_logger);
|
||||
}
|
||||
|
||||
```
|
||||
#### create stdout/stderr logger object
|
||||
---
|
||||
#### Create stdout/stderr logger object
|
||||
```c++
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "spdlog/sinks/stdout_color_sinks.h"
|
||||
@@ -95,6 +99,7 @@ void stdout_example()
|
||||
spdlog::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name)");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
#### Basic file logger
|
||||
```c++
|
||||
@@ -103,7 +108,7 @@ void basic_logfile_example()
|
||||
{
|
||||
try
|
||||
{
|
||||
auto my_logger = spdlog::basic_logger_mt("basic_logger", "logs/basic-log.txt");
|
||||
auto logger = spdlog::basic_logger_mt("basic_logger", "logs/basic-log.txt");
|
||||
}
|
||||
catch (const spdlog::spdlog_ex &ex)
|
||||
{
|
||||
@@ -118,7 +123,9 @@ void basic_logfile_example()
|
||||
void rotating_example()
|
||||
{
|
||||
// Create a file rotating logger with 5mb size max and 3 rotated files
|
||||
auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
|
||||
auto max_size = 1048576 * 5;
|
||||
auto max_files = 3;
|
||||
auto logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", max_size, max_files);
|
||||
}
|
||||
```
|
||||
|
||||
@@ -130,7 +137,7 @@ void rotating_example()
|
||||
void daily_example()
|
||||
{
|
||||
// Create a daily logger - a new file is created every day on 2:30am
|
||||
auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
|
||||
auto logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
|
||||
}
|
||||
|
||||
```
|
||||
@@ -140,7 +147,8 @@ void daily_example()
|
||||
```c++
|
||||
// Loggers can store in a ring buffer all messages (including debug/trace) and display later on demand.
|
||||
// When needed, call dump_backtrace() to see them
|
||||
spdlog::enable_backtrace(32); // create ring buffer with capacity of 32 messages
|
||||
|
||||
spdlog::enable_backtrace(32); // Store the latest 32 messages in a buffer. Older messages will be dropped.
|
||||
// or my_logger->enable_backtrace(32)..
|
||||
for(int i = 0; i < 100; i++)
|
||||
{
|
||||
@@ -156,7 +164,7 @@ spdlog::dump_backtrace(); // log them now! show the last 32 messages
|
||||
#### Periodic flush
|
||||
```c++
|
||||
// periodically flush all *registered* loggers every 3 seconds:
|
||||
// warning: only use if all your loggers are thread safe!
|
||||
// warning: only use if all your loggers are thread safe ("_mt" loggers)
|
||||
spdlog::flush_every(std::chrono::seconds(3));
|
||||
|
||||
```
|
||||
@@ -264,6 +272,37 @@ void user_defined_example()
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
#### User defined flags in the log pattern
|
||||
```c++
|
||||
// Log patterns can contain custom flags.
|
||||
// the following example will add new flag '%*' - which will be bound to a <my_formatter_flag> instance.
|
||||
#include "spdlog/pattern_formatter.h"
|
||||
class my_formatter_flag : public spdlog::custom_flag_formatter
|
||||
{
|
||||
public:
|
||||
void format(const spdlog::details::log_msg &, const std::tm &, spdlog::memory_buf_t &dest) override
|
||||
{
|
||||
std::string some_txt = "custom-flag";
|
||||
dest.append(some_txt.data(), some_txt.data() + some_txt.size());
|
||||
}
|
||||
|
||||
std::unique_ptr<custom_flag_formatter> clone() const override
|
||||
{
|
||||
return spdlog::details::make_unique<my_formatter_flag>();
|
||||
}
|
||||
};
|
||||
|
||||
void custom_flags_example()
|
||||
{
|
||||
auto formatter = std::make_unique<spdlog::pattern_formatter>();
|
||||
formatter->add_flag<my_formatter_flag>('*').set_pattern("[%n] [%*] [%^%l%$] %v");
|
||||
spdlog::set_formatter(std::move(formatter));
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
#### Custom error handler
|
||||
```c++
|
||||
@@ -275,6 +314,7 @@ void err_handler_example()
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
#### syslog
|
||||
```c++
|
||||
@@ -298,6 +338,28 @@ void android_example()
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
#### Load log levels from env variable or from argv
|
||||
|
||||
```c++
|
||||
#include "spdlog/cfg/env.h"
|
||||
int main (int argc, char *argv[])
|
||||
{
|
||||
spdlog::cfg::load_env_levels();
|
||||
// or from command line:
|
||||
// ./example SPDLOG_LEVEL=info,mylogger=trace
|
||||
// #include "spdlog/cfg/argv.h" // for loading levels from argv
|
||||
// spdlog::cfg::load_argv_levels(argc, argv);
|
||||
}
|
||||
```
|
||||
So then you can:
|
||||
|
||||
```console
|
||||
$ export SPDLOG_LEVEL=info,mylogger=trace
|
||||
$ ./example
|
||||
```
|
||||
|
||||
---
|
||||
## Benchmarks
|
||||
|
||||
Below are some [benchmarks](https://github.com/gabime/spdlog/blob/v1.x/bench/bench.cpp) done in Ubuntu 64 bit, Intel i7-4770 CPU @ 3.40GHz
|
||||
@@ -319,21 +381,20 @@ Below are some [benchmarks](https://github.com/gabime/spdlog/blob/v1.x/bench/ben
|
||||
[info] daily_st Elapsed: 0.42 secs 2,393,298/sec
|
||||
[info] null_st Elapsed: 0.04 secs 27,446,957/sec
|
||||
[info] **************************************************************
|
||||
[info] 10 threads sharing same logger, 1,000,000 iterations
|
||||
[info] 10 threads, competing over the same logger object, 1,000,000 iterations
|
||||
[info] **************************************************************
|
||||
[info] basic_mt Elapsed: 0.60 secs 1,659,613/sec
|
||||
[info] rotating_mt Elapsed: 0.62 secs 1,612,493/sec
|
||||
[info] daily_mt Elapsed: 0.61 secs 1,638,305/sec
|
||||
[info] null_mt Elapsed: 0.16 secs 6,272,758/sec
|
||||
```
|
||||
#### ASynchronous mode
|
||||
#### Asynchronous mode
|
||||
```
|
||||
[info] -------------------------------------------------
|
||||
[info] Messages : 1,000,000
|
||||
[info] Threads : 10
|
||||
[info] Queue : 8,192 slots
|
||||
[info] Queue memory : 8,192 x 272 = 2,176 KB
|
||||
[info] Total iters : 3
|
||||
[info] -------------------------------------------------
|
||||
[info]
|
||||
[info] *********************************
|
||||
@@ -354,3 +415,9 @@ Below are some [benchmarks](https://github.com/gabime/spdlog/blob/v1.x/bench/ben
|
||||
|
||||
## Documentation
|
||||
Documentation can be found in the [wiki](https://github.com/gabime/spdlog/wiki/1.-QuickStart) pages.
|
||||
|
||||
---
|
||||
|
||||
Thanks to [JetBrains](https://www.jetbrains.com/?from=spdlog) for donating licenses to their products to help developing **spdlog** <a href="https://www.jetbrains.com/?from=spdlog"><img src="logos/jetbrains-variant-4.svg" width="94" align="center" /></a>
|
||||
|
||||
|
||||
|
63
appveyor.yml
63
appveyor.yml
@@ -1,34 +1,51 @@
|
||||
version: 1.0.{build}
|
||||
image: Visual Studio 2015
|
||||
image: Visual Studio 2017
|
||||
environment:
|
||||
matrix:
|
||||
- GENERATOR: '"MinGW Makefiles"'
|
||||
BUILD_TYPE: Debug
|
||||
- GENERATOR: '"MinGW Makefiles"'
|
||||
BUILD_TYPE: Release
|
||||
- GENERATOR: '"Visual Studio 14 2015"'
|
||||
BUILD_TYPE: Debug
|
||||
- GENERATOR: '"Visual Studio 14 2015"'
|
||||
BUILD_TYPE: Release
|
||||
- GENERATOR: '"Visual Studio 14 2015 Win64"'
|
||||
BUILD_TYPE: Debug
|
||||
- GENERATOR: '"Visual Studio 14 2015 Win64"'
|
||||
BUILD_TYPE: Release
|
||||
- GENERATOR: '"Visual Studio 14 2015"'
|
||||
BUILD_TYPE: Debug
|
||||
WCHAR: 'OFF'
|
||||
BUILD_SHARED: 'OFF'
|
||||
- GENERATOR: '"Visual Studio 14 2015"'
|
||||
BUILD_TYPE: Release
|
||||
WCHAR: 'ON'
|
||||
BUILD_SHARED: 'OFF'
|
||||
- GENERATOR: '"Visual Studio 14 2015 Win64"'
|
||||
BUILD_TYPE: Debug
|
||||
WCHAR: 'ON'
|
||||
BUILD_SHARED: 'OFF'
|
||||
- GENERATOR: '"Visual Studio 14 2015 Win64"'
|
||||
BUILD_TYPE: Release
|
||||
WCHAR: 'ON'
|
||||
BUILD_SHARED: 'OFF'
|
||||
- GENERATOR: '"Visual Studio 15 2017 Win64"'
|
||||
BUILD_TYPE: Debug
|
||||
WCHAR: 'ON'
|
||||
BUILD_SHARED: 'OFF'
|
||||
- GENERATOR: '"Visual Studio 15 2017 Win64"'
|
||||
BUILD_TYPE: Release
|
||||
WCHAR: 'OFF'
|
||||
BUILD_SHARED: 'OFF'
|
||||
- GENERATOR: '"Visual Studio 15 2017 Win64"'
|
||||
BUILD_TYPE: Release
|
||||
WCHAR: 'OFF'
|
||||
BUILD_SHARED: 'ON'
|
||||
build_script:
|
||||
- cmd: >-
|
||||
set
|
||||
- cmd: >-
|
||||
set
|
||||
|
||||
mkdir build
|
||||
mkdir build
|
||||
|
||||
cd build
|
||||
cd build
|
||||
|
||||
set PATH=%PATH:C:\Program Files\Git\usr\bin;=%
|
||||
set PATH=%PATH%;C:\Program Files\Git\usr\bin
|
||||
|
||||
set PATH=C:\mingw-w64\i686-5.3.0-posix-dwarf-rt_v4-rev0\mingw32\bin;%PATH%
|
||||
cmake .. -G %GENERATOR% -DCMAKE_BUILD_TYPE=%BUILD_TYPE% -DSPDLOG_WCHAR_SUPPORT=%WCHAR% -DSPDLOG_BUILD_SHARED=%BUILD_SHARED% -DSPDLOG_BUILD_EXAMPLE=ON -DSPDLOG_BUILD_EXAMPLE_HO=ON -DSPDLOG_BUILD_TESTS=ON -DSPDLOG_BUILD_TESTS_HO=OFF -DSPDLOG_ENABLE_WARNINGS=ON
|
||||
|
||||
cmake .. -G %GENERATOR% -DCMAKE_BUILD_TYPE=%BUILD_TYPE% -DSPDLOG_WCHAR_SUPPORT=ON -DSPDLOG_BUILD_EXAMPLE=ON -DSPDLOG_BUILD_EXAMPLE_HO=ON -DSPDLOG_BUILD_TESTS=ON -DSPDLOG_BUILD_TESTS_HO=OFF
|
||||
|
||||
cmake --build . --config %BUILD_TYPE%
|
||||
cmake --build . --config %BUILD_TYPE%
|
||||
|
||||
before_test:
|
||||
- set PATH=%PATH%;C:\projects\spdlog\build\%BUILD_TYPE%
|
||||
|
||||
test_script:
|
||||
- ctest -VV -C "%BUILD_TYPE%"
|
||||
- C:\projects\spdlog\build\tests\%BUILD_TYPE%\spdlog-utests.exe
|
||||
|
@@ -1,12 +1,11 @@
|
||||
# Copyright(c) 2019 spdlog authors
|
||||
# Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
# Copyright(c) 2019 spdlog authors Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
cmake_minimum_required(VERSION 3.1)
|
||||
project(spdlog_bench CXX)
|
||||
|
||||
if(NOT TARGET spdlog)
|
||||
# Stand-alone build
|
||||
find_package(spdlog CONFIG REQUIRED)
|
||||
# Stand-alone build
|
||||
find_package(spdlog CONFIG REQUIRED)
|
||||
endif()
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
@@ -24,5 +23,3 @@ target_link_libraries(latency PRIVATE benchmark::benchmark spdlog::spdlog)
|
||||
|
||||
add_executable(formatter-bench formatter-bench.cpp)
|
||||
target_link_libraries(formatter-bench PRIVATE benchmark::benchmark spdlog::spdlog)
|
||||
|
||||
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs")
|
||||
|
@@ -19,21 +19,17 @@
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
using namespace std;
|
||||
using namespace std::chrono;
|
||||
using namespace spdlog;
|
||||
using namespace spdlog::sinks;
|
||||
using namespace utils;
|
||||
|
||||
void bench(int howmany, std::shared_ptr<spdlog::logger> log);
|
||||
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);
|
||||
void bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log);
|
||||
void bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log);
|
||||
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, size_t thread_count);
|
||||
|
||||
static size_t file_size = 30 * 1024 * 1024;
|
||||
static size_t rotating_files = 5;
|
||||
// void bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log);
|
||||
// void bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log);
|
||||
|
||||
void bench_threaded_logging(int threads, int iters)
|
||||
static const size_t file_size = 30 * 1024 * 1024;
|
||||
static const size_t rotating_files = 5;
|
||||
static const int max_threads = 1000;
|
||||
|
||||
void bench_threaded_logging(size_t threads, int iters)
|
||||
{
|
||||
spdlog::info("**************************************************************");
|
||||
spdlog::info("Multi threaded: {:n} threads, {:n} messages", threads, iters);
|
||||
@@ -111,14 +107,23 @@ int main(int argc, char *argv[])
|
||||
spdlog::set_automatic_registration(false);
|
||||
spdlog::default_logger()->set_pattern("[%^%l%$] %v");
|
||||
int iters = 250000;
|
||||
int threads = 4;
|
||||
size_t threads = 4;
|
||||
try
|
||||
{
|
||||
|
||||
if (argc > 1)
|
||||
iters = atoi(argv[1]);
|
||||
{
|
||||
iters = std::stoi(argv[1]);
|
||||
}
|
||||
if (argc > 2)
|
||||
threads = atoi(argv[2]);
|
||||
{
|
||||
threads = std::stoul(argv[2]);
|
||||
}
|
||||
|
||||
if (threads > max_threads)
|
||||
{
|
||||
throw std::runtime_error(fmt::format("Number of threads exceeds maximum({}})", max_threads));
|
||||
}
|
||||
|
||||
bench_single_threaded(iters);
|
||||
bench_threaded_logging(1, iters);
|
||||
@@ -134,7 +139,10 @@ int main(int argc, char *argv[])
|
||||
|
||||
void bench(int howmany, std::shared_ptr<spdlog::logger> log)
|
||||
{
|
||||
using std::chrono::duration;
|
||||
using std::chrono::duration_cast;
|
||||
using std::chrono::high_resolution_clock;
|
||||
|
||||
auto start = high_resolution_clock::now();
|
||||
for (auto i = 0; i < howmany; ++i)
|
||||
{
|
||||
@@ -148,19 +156,23 @@ void bench(int howmany, std::shared_ptr<spdlog::logger> log)
|
||||
spdlog::drop(log->name());
|
||||
}
|
||||
|
||||
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count)
|
||||
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, size_t thread_count)
|
||||
{
|
||||
using std::chrono::duration;
|
||||
using std::chrono::duration_cast;
|
||||
using std::chrono::high_resolution_clock;
|
||||
vector<thread> threads;
|
||||
|
||||
std::vector<std::thread> threads;
|
||||
threads.reserve(thread_count);
|
||||
auto start = high_resolution_clock::now();
|
||||
for (int t = 0; t < thread_count; ++t)
|
||||
for (size_t t = 0; t < thread_count; ++t)
|
||||
{
|
||||
threads.push_back(std::thread([&]() {
|
||||
for (int j = 0; j < howmany / thread_count; j++)
|
||||
threads.emplace_back([&]() {
|
||||
for (int j = 0; j < howmany / static_cast<int>(thread_count); j++)
|
||||
{
|
||||
log->info("Hello logger: msg number {}", j);
|
||||
}
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
for (auto &t : threads)
|
||||
@@ -174,9 +186,13 @@ void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count
|
||||
spdlog::drop(log->name());
|
||||
}
|
||||
|
||||
/*
|
||||
void bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log)
|
||||
{
|
||||
using std::chrono::high_resolution_clock;
|
||||
using std::chrono::duration;
|
||||
using std::chrono::duration_cast;
|
||||
|
||||
auto orig_default = spdlog::default_logger();
|
||||
spdlog::set_default_logger(log);
|
||||
auto start = high_resolution_clock::now();
|
||||
@@ -194,18 +210,22 @@ void bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log)
|
||||
|
||||
void bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log)
|
||||
{
|
||||
using std::chrono::high_resolution_clock;
|
||||
using std::chrono::duration;
|
||||
using std::chrono::duration_cast;
|
||||
|
||||
const char *msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pharetra metus cursus "
|
||||
"lacus placerat congue. Nulla egestas, mauris a tincidunt tempus, enim lectus volutpat mi, eu consequat sem "
|
||||
"libero nec massa. In dapibus ipsum a diam rhoncus gravida. Etiam non dapibus eros. Donec fringilla dui sed "
|
||||
"augue pretium, nec scelerisque est maximus. Nullam convallis, sem nec blandit maximus, nisi turpis ornare "
|
||||
"nisl, sit amet volutpat neque massa eu odio. Maecenas malesuada quam ex, posuere congue nibh turpis duis.";
|
||||
using std::chrono::high_resolution_clock;
|
||||
|
||||
auto orig_default = spdlog::default_logger();
|
||||
spdlog::set_default_logger(log);
|
||||
auto start = high_resolution_clock::now();
|
||||
for (auto i = 0; i < howmany; ++i)
|
||||
{
|
||||
spdlog::log(level::info, msg);
|
||||
spdlog::log(spdlog::level::info, msg);
|
||||
}
|
||||
|
||||
auto delta = high_resolution_clock::now() - start;
|
||||
@@ -214,3 +234,5 @@ void bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log)
|
||||
spdlog::set_default_logger(std::move(orig_default));
|
||||
spdlog::info("{:<30} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
|
||||
}
|
||||
|
||||
*/
|
@@ -6,7 +6,7 @@
|
||||
#include "benchmark/benchmark.h"
|
||||
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "spdlog/details/pattern_formatter.h"
|
||||
#include "spdlog/pattern_formatter.h"
|
||||
|
||||
void bench_formatter(benchmark::State &state, std::string pattern)
|
||||
{
|
||||
|
@@ -16,26 +16,6 @@
|
||||
#include "spdlog/sinks/null_sink.h"
|
||||
#include "spdlog/sinks/rotating_file_sink.h"
|
||||
|
||||
void prepare_logdir()
|
||||
{
|
||||
spdlog::info("Preparing latency_logs directory..");
|
||||
#ifdef _WIN32
|
||||
system("if not exist logs mkdir latency_logs");
|
||||
system("del /F /Q logs\\*");
|
||||
#else
|
||||
auto rv = system("mkdir -p latency_logs");
|
||||
if (rv != 0)
|
||||
{
|
||||
throw std::runtime_error("Failed to mkdir -p latency_logs");
|
||||
}
|
||||
rv = system("rm -f latency_logs/*");
|
||||
if (rv != 0)
|
||||
{
|
||||
throw std::runtime_error("Failed to rm -f latency_logs/*");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void bench_c_string(benchmark::State &state, std::shared_ptr<spdlog::logger> logger)
|
||||
{
|
||||
const char *msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pharetra metus cursus "
|
||||
@@ -71,11 +51,21 @@ void bench_disabled_macro(benchmark::State &state, std::shared_ptr<spdlog::logge
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef __linux__
|
||||
void bench_dev_null()
|
||||
{
|
||||
auto dev_null_st = spdlog::basic_logger_st("/dev/null_st", "/dev/null");
|
||||
benchmark::RegisterBenchmark("/dev/null_st", bench_logger, std::move(dev_null_st))->UseRealTime();
|
||||
spdlog::drop("/dev/null_st");
|
||||
|
||||
auto dev_null_mt = spdlog::basic_logger_mt("/dev/null_mt", "/dev/null");
|
||||
benchmark::RegisterBenchmark("/dev/null_mt", bench_logger, std::move(dev_null_mt))->UseRealTime();
|
||||
spdlog::drop("/dev/null_mt");
|
||||
}
|
||||
#endif // __linux__
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
|
||||
using spdlog::sinks::basic_file_sink_mt;
|
||||
using spdlog::sinks::basic_file_sink_st;
|
||||
using spdlog::sinks::null_sink_mt;
|
||||
using spdlog::sinks::null_sink_st;
|
||||
|
||||
@@ -83,7 +73,7 @@ int main(int argc, char *argv[])
|
||||
size_t rotating_files = 5;
|
||||
int n_threads = benchmark::CPUInfo::Get().num_cpus;
|
||||
|
||||
prepare_logdir();
|
||||
auto full_bench = argc > 1 && std::string(argv[1]) == "full";
|
||||
|
||||
// disabled loggers
|
||||
auto disabled_logger = std::make_shared<spdlog::logger>("bench", std::make_shared<null_sink_mt>());
|
||||
@@ -103,54 +93,61 @@ int main(int argc, char *argv[])
|
||||
tracing_null_logger_st->enable_backtrace(64);
|
||||
benchmark::RegisterBenchmark("null_sink_st/backtrace", bench_logger, tracing_null_logger_st);
|
||||
|
||||
// basic_st
|
||||
auto basic_st = spdlog::basic_logger_st("basic_st", "latency_logs/basic_st.log", true);
|
||||
benchmark::RegisterBenchmark("basic_st", bench_logger, std::move(basic_st))->UseRealTime();
|
||||
spdlog::drop("basic_st");
|
||||
// with backtrace of 64
|
||||
auto tracing_basic_st = spdlog::basic_logger_st("tracing_basic_st", "latency_logs/tracing_basic_st.log", true);
|
||||
tracing_basic_st->enable_backtrace(64);
|
||||
benchmark::RegisterBenchmark("basic_st/backtrace", bench_logger, std::move(tracing_basic_st))->UseRealTime();
|
||||
spdlog::drop("tracing_basic_st");
|
||||
#ifdef __linux
|
||||
bench_dev_null();
|
||||
#endif // __linux__
|
||||
|
||||
// rotating st
|
||||
auto rotating_st = spdlog::rotating_logger_st("rotating_st", "latency_logs/rotating_st.log", file_size, rotating_files);
|
||||
benchmark::RegisterBenchmark("rotating_st", bench_logger, std::move(rotating_st))->UseRealTime();
|
||||
spdlog::drop("rotating_st");
|
||||
// with backtrace of 64
|
||||
auto tracing_rotating_st =
|
||||
spdlog::rotating_logger_st("tracing_rotating_st", "latency_logs/tracing_rotating_st.log", file_size, rotating_files);
|
||||
benchmark::RegisterBenchmark("rotating_st/backtrace", bench_logger, std::move(tracing_rotating_st))->UseRealTime();
|
||||
spdlog::drop("tracing_rotating_st");
|
||||
if (full_bench)
|
||||
{
|
||||
// basic_st
|
||||
auto basic_st = spdlog::basic_logger_st("basic_st", "latency_logs/basic_st.log", true);
|
||||
benchmark::RegisterBenchmark("basic_st", bench_logger, std::move(basic_st))->UseRealTime();
|
||||
spdlog::drop("basic_st");
|
||||
// with backtrace of 64
|
||||
auto tracing_basic_st = spdlog::basic_logger_st("tracing_basic_st", "latency_logs/tracing_basic_st.log", true);
|
||||
tracing_basic_st->enable_backtrace(64);
|
||||
benchmark::RegisterBenchmark("basic_st/backtrace", bench_logger, std::move(tracing_basic_st))->UseRealTime();
|
||||
spdlog::drop("tracing_basic_st");
|
||||
|
||||
// daily st
|
||||
auto daily_st = spdlog::daily_logger_mt("daily_st", "latency_logs/daily_st.log");
|
||||
benchmark::RegisterBenchmark("daily_st", bench_logger, std::move(daily_st))->UseRealTime();
|
||||
spdlog::drop("daily_st");
|
||||
auto tracing_daily_st = spdlog::daily_logger_mt("tracing_daily_st", "latency_logs/daily_st.log");
|
||||
benchmark::RegisterBenchmark("daily_st/backtrace", bench_logger, std::move(tracing_daily_st))->UseRealTime();
|
||||
spdlog::drop("tracing_daily_st");
|
||||
// rotating st
|
||||
auto rotating_st = spdlog::rotating_logger_st("rotating_st", "latency_logs/rotating_st.log", file_size, rotating_files);
|
||||
benchmark::RegisterBenchmark("rotating_st", bench_logger, std::move(rotating_st))->UseRealTime();
|
||||
spdlog::drop("rotating_st");
|
||||
// with backtrace of 64
|
||||
auto tracing_rotating_st =
|
||||
spdlog::rotating_logger_st("tracing_rotating_st", "latency_logs/tracing_rotating_st.log", file_size, rotating_files);
|
||||
benchmark::RegisterBenchmark("rotating_st/backtrace", bench_logger, std::move(tracing_rotating_st))->UseRealTime();
|
||||
spdlog::drop("tracing_rotating_st");
|
||||
|
||||
//
|
||||
// Multi threaded bench, 10 loggers using same logger concurrently
|
||||
//
|
||||
auto null_logger_mt = std::make_shared<spdlog::logger>("bench", std::make_shared<null_sink_mt>());
|
||||
benchmark::RegisterBenchmark("null_sink_mt", bench_logger, null_logger_mt)->Threads(n_threads)->UseRealTime();
|
||||
// daily st
|
||||
auto daily_st = spdlog::daily_logger_mt("daily_st", "latency_logs/daily_st.log");
|
||||
benchmark::RegisterBenchmark("daily_st", bench_logger, std::move(daily_st))->UseRealTime();
|
||||
spdlog::drop("daily_st");
|
||||
auto tracing_daily_st = spdlog::daily_logger_mt("tracing_daily_st", "latency_logs/daily_st.log");
|
||||
benchmark::RegisterBenchmark("daily_st/backtrace", bench_logger, std::move(tracing_daily_st))->UseRealTime();
|
||||
spdlog::drop("tracing_daily_st");
|
||||
|
||||
// basic_mt
|
||||
auto basic_mt = spdlog::basic_logger_mt("basic_mt", "latency_logs/basic_mt.log", true);
|
||||
benchmark::RegisterBenchmark("basic_mt", bench_logger, std::move(basic_mt))->Threads(n_threads)->UseRealTime();
|
||||
spdlog::drop("basic_mt");
|
||||
//
|
||||
// Multi threaded bench, 10 loggers using same logger concurrently
|
||||
//
|
||||
auto null_logger_mt = std::make_shared<spdlog::logger>("bench", std::make_shared<null_sink_mt>());
|
||||
benchmark::RegisterBenchmark("null_sink_mt", bench_logger, null_logger_mt)->Threads(n_threads)->UseRealTime();
|
||||
|
||||
// rotating mt
|
||||
auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "latency_logs/rotating_mt.log", file_size, rotating_files);
|
||||
benchmark::RegisterBenchmark("rotating_mt", bench_logger, std::move(rotating_mt))->Threads(n_threads)->UseRealTime();
|
||||
spdlog::drop("rotating_mt");
|
||||
// basic_mt
|
||||
auto basic_mt = spdlog::basic_logger_mt("basic_mt", "latency_logs/basic_mt.log", true);
|
||||
benchmark::RegisterBenchmark("basic_mt", bench_logger, std::move(basic_mt))->Threads(n_threads)->UseRealTime();
|
||||
spdlog::drop("basic_mt");
|
||||
|
||||
// daily mt
|
||||
auto daily_mt = spdlog::daily_logger_mt("daily_mt", "latency_logs/daily_mt.log");
|
||||
benchmark::RegisterBenchmark("daily_mt", bench_logger, std::move(daily_mt))->Threads(n_threads)->UseRealTime();
|
||||
spdlog::drop("daily_mt");
|
||||
// rotating mt
|
||||
auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "latency_logs/rotating_mt.log", file_size, rotating_files);
|
||||
benchmark::RegisterBenchmark("rotating_mt", bench_logger, std::move(rotating_mt))->Threads(n_threads)->UseRealTime();
|
||||
spdlog::drop("rotating_mt");
|
||||
|
||||
// daily mt
|
||||
auto daily_mt = spdlog::daily_logger_mt("daily_mt", "latency_logs/daily_mt.log");
|
||||
benchmark::RegisterBenchmark("daily_mt", bench_logger, std::move(daily_mt))->Threads(n_threads)->UseRealTime();
|
||||
spdlog::drop("daily_mt");
|
||||
}
|
||||
|
||||
// async
|
||||
auto queue_size = 1024 * 1024 * 3;
|
||||
|
@@ -1,15 +0,0 @@
|
||||
benchmark = dependency('benchmark')
|
||||
|
||||
bench_matrix = [
|
||||
['bench', [spdlog_dep], []],
|
||||
['async_bench', [spdlog_dep], []],
|
||||
['formatter-bench', [spdlog_dep, benchmark], ['all']],
|
||||
['latency', [spdlog_dep, benchmark], []],
|
||||
]
|
||||
|
||||
foreach i : bench_matrix
|
||||
bench_exe = executable(i[0], i[0] + '.cpp', dependencies: i[1])
|
||||
benchmark('bench_' + i[0], bench_exe, args: i[2])
|
||||
endforeach
|
||||
|
||||
run_command(find_program('mkdir'), meson.current_build_dir() + '/logs')
|
@@ -1,6 +1,6 @@
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# IDE support for headers
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
set(SPDLOG_HEADERS_DIR "${CMAKE_CURRENT_LIST_DIR}/../include")
|
||||
|
||||
file(GLOB SPDLOG_TOP_HEADERS "${SPDLOG_HEADERS_DIR}/spdlog/*.h")
|
||||
@@ -8,11 +8,11 @@ file(GLOB SPDLOG_DETAILS_HEADERS "${SPDLOG_HEADERS_DIR}/spdlog/details/*.h")
|
||||
file(GLOB SPDLOG_SINKS_HEADERS "${SPDLOG_HEADERS_DIR}/spdlog/sinks/*.h")
|
||||
file(GLOB SPDLOG_FMT_HEADERS "${SPDLOG_HEADERS_DIR}/spdlog/fmt/*.h")
|
||||
file(GLOB SPDLOG_FMT_BUNDELED_HEADERS "${SPDLOG_HEADERS_DIR}/spdlog/fmt/bundled/*.h")
|
||||
set(SPDLOG_ALL_HEADERS ${SPDLOG_TOP_HEADERS} ${SPDLOG_DETAILS_HEADERS} ${SPDLOG_SINKS_HEADERS} ${SPDLOG_FMT_HEADERS} ${SPDLOG_FMT_BUNDELED_HEADERS})
|
||||
set(SPDLOG_ALL_HEADERS ${SPDLOG_TOP_HEADERS} ${SPDLOG_DETAILS_HEADERS} ${SPDLOG_SINKS_HEADERS} ${SPDLOG_FMT_HEADERS}
|
||||
${SPDLOG_FMT_BUNDELED_HEADERS})
|
||||
|
||||
source_group("Header Files\\spdlog" FILES ${SPDLOG_TOP_HEADERS})
|
||||
source_group("Header Files\\spdlog\\details" FILES ${SPDLOG_DETAILS_HEADERS})
|
||||
source_group("Header Files\\spdlog\\sinks" FILES ${SPDLOG_SINKS_HEADERS})
|
||||
source_group("Header Files\\spdlog\\fmt" FILES ${SPDLOG_FMT_HEADERS})
|
||||
source_group("Header Files\\spdlog\\fmt\\bundled\\" FILES ${SPDLOG_FMT_BUNDELED_HEADERS})
|
||||
|
||||
|
258
cmake/pch.h.in
Normal file
258
cmake/pch.h.in
Normal file
@@ -0,0 +1,258 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
// details/pattern_formatter-inl.h
|
||||
// fmt/bin_to_hex.h
|
||||
// fmt/bundled/format-inl.h
|
||||
#include <cctype>
|
||||
|
||||
// details/file_helper-inl.h
|
||||
// details/os-inl.h
|
||||
// fmt/bundled/core.h
|
||||
// fmt/bundled/posix.h
|
||||
// logger-inl.h
|
||||
// sinks/daily_file_sink.h
|
||||
// sinks/stdout_sinks.h
|
||||
#include <cstdio>
|
||||
|
||||
// details/os-inl.h
|
||||
// fmt/bundled/posix.h
|
||||
#include <cstdlib>
|
||||
|
||||
// details/os-inl.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// fmt/bundled/core.h
|
||||
// fmt/bundled/format-inl.h
|
||||
#include <cstring>
|
||||
|
||||
// details/os-inl.h
|
||||
// details/os.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// details/pattern_formatter.h
|
||||
// fmt/bundled/chrono.h
|
||||
// sinks/daily_file_sink.h
|
||||
// sinks/rotating_file_sink-inl.h
|
||||
#include <ctime>
|
||||
|
||||
// fmt/bundled/format-inl.h
|
||||
#include <climits>
|
||||
|
||||
// fmt/bundled/format-inl.h
|
||||
#include <cwchar>
|
||||
|
||||
// fmt/bundled/format-inl.h
|
||||
// fmt/bundled/format.h
|
||||
#include <cmath>
|
||||
|
||||
// fmt/bundled/format-inl.h
|
||||
#include <cstdarg>
|
||||
|
||||
// details/file_helper-inl.h
|
||||
// fmt/bundled/format.h
|
||||
// fmt/bundled/posix.h
|
||||
// sinks/rotating_file_sink-inl.h
|
||||
#include <cerrno>
|
||||
|
||||
// details/circular_q.h
|
||||
// details/thread_pool-inl.h
|
||||
// fmt/bundled/format-inl.h
|
||||
#include <cassert>
|
||||
|
||||
// async_logger-inl.h
|
||||
// cfg/helpers-inl.h
|
||||
// log_levels.h
|
||||
// common.h
|
||||
// details/file_helper-inl.h
|
||||
// details/log_msg.h
|
||||
// details/os-inl.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// details/pattern_formatter.h
|
||||
// details/registry-inl.h
|
||||
// details/registry.h
|
||||
// details/tcp_client-windows.h
|
||||
// details/tcp_client.h
|
||||
// fmt/bundled/core.h
|
||||
// sinks/android_sink.h
|
||||
// sinks/ansicolor_sink.h
|
||||
// sinks/basic_file_sink.h
|
||||
// sinks/daily_file_sink.h
|
||||
// sinks/dup_filter_sink.h
|
||||
// sinks/msvc_sink.h
|
||||
// sinks/ringbuffer_sink.h
|
||||
// sinks/rotating_file_sink-inl.h
|
||||
// sinks/rotating_file_sink.h
|
||||
// sinks/syslog_sink.h
|
||||
// sinks/tcp_sink.h
|
||||
// sinks/win_eventlog_sink.h
|
||||
// sinks/wincolor_sink.h
|
||||
// spdlog.h:
|
||||
#include <string>
|
||||
|
||||
// cfg/helpers-inl.h
|
||||
// fmt/bundled/chrono.h
|
||||
#include <sstream>
|
||||
|
||||
// fmt/bundled/ostream.h
|
||||
// sinks/ostream_sink.h
|
||||
#include <ostream>
|
||||
|
||||
// cfg/log_levels.h
|
||||
// details/registry-inl.h
|
||||
// details/registry.h
|
||||
#include <unordered_map>
|
||||
|
||||
// details/circular_q.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// details/pattern_formatter.h
|
||||
// details/thread_pool.h
|
||||
// fmt/bundled/compile.h
|
||||
// logger.h
|
||||
// sinks/dist_sink.h
|
||||
// sinks/ringbuffer_sink.h
|
||||
// sinks/win_eventlog_sink.h
|
||||
#include <vector>
|
||||
|
||||
// details/os-inl.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// sinks/ansicolor_sink.h
|
||||
// sinks/syslog_sink.h
|
||||
// sinks/systemd_sink.h
|
||||
// sinks/wincolor_sink.h
|
||||
#include <array>
|
||||
|
||||
// details/file_helper-inl.h
|
||||
// details/file_helper.h
|
||||
// sinks/rotating_file_sink-inl.h
|
||||
#include <tuple>
|
||||
|
||||
// details/os-inl.h
|
||||
// fmt/bundled/format.h
|
||||
// fmt/bundled/printf.h
|
||||
#include <limits>
|
||||
|
||||
// common.h
|
||||
// details/backtracer.h
|
||||
// details/null_mutex.h
|
||||
#include <atomic>
|
||||
|
||||
// common.h
|
||||
// details/backtracer.h
|
||||
// details/null_mutex.h
|
||||
#include <locale>
|
||||
|
||||
// common.h
|
||||
#include <initializer_list>
|
||||
|
||||
// common.h
|
||||
#include <exception>
|
||||
|
||||
// common.h
|
||||
// details/fmt_helper.h
|
||||
// fmt/bundled/core.h
|
||||
// fmt/bundled/ranges.h
|
||||
#include <type_traits>
|
||||
|
||||
// cfg/helpers-inl.h
|
||||
// details/null_mutex.h
|
||||
// details/pattern_formatter-inl.h
|
||||
#include <utility>
|
||||
|
||||
// async.h
|
||||
// async_logger-inl.h
|
||||
// common.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// details/pattern_formatter.h
|
||||
// details/registry-inl.h
|
||||
// details/registry.h
|
||||
// details/thread_pool.h
|
||||
// fmt/bundled/format.h
|
||||
// sinks/ansicolor_sink.h
|
||||
// sinks/base_sink-inl.h
|
||||
// sinks/dist_sink.h
|
||||
// sinks/stdout_sinks-inl.h
|
||||
// sinks/wincolor_sink.h
|
||||
// spdlog.h
|
||||
#include <memory>
|
||||
|
||||
// async.h
|
||||
// common.h
|
||||
// details/backtracer.h
|
||||
// details/periodic_worker.h
|
||||
// details/registry-inl.h
|
||||
// details/registry.h
|
||||
// details/thread_pool.h
|
||||
// sinks/tcp_sink.h
|
||||
// spdlog.h
|
||||
#include <functional>
|
||||
|
||||
// details/mpmc_blocking_q.h
|
||||
// details/periodic_worker.h
|
||||
#include <condition_variable>
|
||||
|
||||
// details/os-inl.h
|
||||
// fmt/bundled/format.h
|
||||
// fmt/bundled/printf.h
|
||||
// sinks/dist_sink.h
|
||||
#include <algorithm>
|
||||
|
||||
// common.h
|
||||
// details/file_helper-inl.h
|
||||
// details/fmt_helper.h
|
||||
// details/os-inl.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// details/pattern_formatter.h
|
||||
// details/periodic_worker.h
|
||||
// details/registry-inl.h
|
||||
// details/registry.h
|
||||
// details/thread_pool.h
|
||||
// fmt/bundled/chrono.h
|
||||
// sinks/android_sink.h
|
||||
// sinks/daily_file_sink.h
|
||||
// sinks/dup_filter_sink.h
|
||||
// sinks/rotating_file_sink-inl.h
|
||||
// sinks/rotating_file_sink.h
|
||||
// sinks/tcp_sink.h
|
||||
// spdlog.h
|
||||
#include <chrono>
|
||||
|
||||
// details/file_helper-inl.h
|
||||
// details/os-inl.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// details/periodic_worker.h
|
||||
// details/thread_pool.h
|
||||
// sinks/android_sink.h
|
||||
#include <thread>
|
||||
|
||||
// async.h
|
||||
// details/backtracer.h
|
||||
// details/console_globals.h
|
||||
// details/mpmc_blocking_q.h
|
||||
// details/pattern_formatter-inl.h
|
||||
// details/periodic_worker.h
|
||||
// details/registry.h
|
||||
// sinks/android_sink.h
|
||||
// sinks/ansicolor_sink.h
|
||||
// sinks/basic_file_sink.h
|
||||
// sinks/daily_file_sink.h
|
||||
// sinks/dist_sink.h
|
||||
// sinks/dup_filter_sink.h
|
||||
// sinks/msvc_sink.h
|
||||
// sinks/null_sink.h
|
||||
// sinks/ostream_sink.h
|
||||
// sinks/ringbuffer_sink.h
|
||||
// sinks/rotating_file_sink-inl.h
|
||||
// sinks/rotating_file_sink.h
|
||||
// sinks/tcp_sink.h
|
||||
// sinks/win_eventlog_sink.h
|
||||
// sinks/wincolor_sink.h
|
||||
//
|
||||
// color_sinks.cpp
|
||||
// file_sinks.cpp
|
||||
// spdlog.cpp
|
||||
// stdout_sinks.cpp
|
||||
#include <mutex>
|
||||
|
||||
// spdlog
|
||||
#include <spdlog/common.h>
|
@@ -7,5 +7,7 @@ Name: lib@PROJECT_NAME@
|
||||
Description: Fast C++ logging library.
|
||||
URL: https://github.com/gabime/@PROJECT_NAME@
|
||||
Version: @SPDLOG_VERSION@
|
||||
CFlags: -I${includedir}/@SPDLOG_CFLAGS@
|
||||
Libs: -L${libdir}/@PROJECT_NAME@ -l@PROJECT_NAME@
|
||||
CFlags: -I${includedir} @PKG_CONFIG_DEFINES@
|
||||
Libs: -L${libdir} -lspdlog -pthread
|
||||
Requires: @PKG_CONFIG_REQUIRES@
|
||||
|
||||
|
@@ -1,26 +1,46 @@
|
||||
set(CPACK_GENERATOR
|
||||
TGZ
|
||||
ZIP
|
||||
)
|
||||
set(CPACK_GENERATOR "TGZ;ZIP" CACHE STRING "Semicolon separated list of generators")
|
||||
|
||||
set(CPACK_INCLUDE_TOPLEVEL_DIRECTORY 0)
|
||||
set(CPACK_INSTALL_CMAKE_PROJECTS
|
||||
"${CMAKE_BINARY_DIR}"
|
||||
"${PROJECT_NAME}"
|
||||
ALL
|
||||
.
|
||||
)
|
||||
set(CPACK_INSTALL_CMAKE_PROJECTS "${CMAKE_BINARY_DIR}" "${PROJECT_NAME}" ALL .)
|
||||
|
||||
set(CPACK_PROJECT_URL "https://github.com/gabime/spdlog")
|
||||
set(CPACK_PACKAGE_VENDOR "Gabi Melman")
|
||||
set(CPACK_PACKAGE_CONTACT "Gabi Melman <gmelman1@gmail.com>")
|
||||
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Fast C++ logging library")
|
||||
set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR})
|
||||
set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR})
|
||||
set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH})
|
||||
set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH})
|
||||
if (PROJECT_VERSION_TWEAK)
|
||||
if(PROJECT_VERSION_TWEAK)
|
||||
set(CPACK_PACKAGE_VERSION ${CPACK_PACKAGE_VERSION}.${PROJECT_VERSION_TWEAK})
|
||||
endif ()
|
||||
set(CPACK_PACKAGE_RELOCATABLE ON)
|
||||
endif()
|
||||
set(CPACK_PACKAGE_RELOCATABLE ON CACHE BOOL "Build relocatable package")
|
||||
|
||||
set(CPACK_RPM_PACKAGE_LICENSE "MIT")
|
||||
set(CPACK_RPM_PACKAGE_GROUP "Development/Libraries")
|
||||
set(CPACK_RPM_PACKAGE_URL ${CPACK_PROJECT_URL})
|
||||
set(CPACK_RPM_PACKAGE_DESCRIPTION "Very fast, header-only/compiled, C++ logging library.")
|
||||
|
||||
if(CPACK_PACKAGE_NAME)
|
||||
set(CPACK_RPM_FILE_NAME "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}")
|
||||
else()
|
||||
set(CPACK_RPM_FILE_NAME "${PROJECT_NAME}-${CPACK_PACKAGE_VERSION}")
|
||||
endif()
|
||||
|
||||
if(CPACK_RPM_PACKAGE_RELEASE)
|
||||
set(CPACK_RPM_FILE_NAME "${CPACK_RPM_FILE_NAME}-${CPACK_RPM_PACKAGE_RELEASE}")
|
||||
endif()
|
||||
|
||||
if(CPACK_RPM_PACKAGE_ARCHITECTURE)
|
||||
set(CPACK_RPM_FILE_NAME "${CPACK_RPM_FILE_NAME}.${CPACK_RPM_PACKAGE_ARCHITECTURE}")
|
||||
endif()
|
||||
set(CPACK_RPM_FILE_NAME "${CPACK_RPM_FILE_NAME}.rpm")
|
||||
|
||||
if(NOT CPACK_PACKAGE_RELOCATABLE)
|
||||
# Depend on pkgconfig rpm to create the system pkgconfig folder
|
||||
set(CPACK_RPM_PACKAGE_REQUIRES pkgconfig)
|
||||
set(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION
|
||||
"${CPACK_PACKAGING_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/pkgconfig")
|
||||
endif()
|
||||
|
||||
include(CPack)
|
||||
|
@@ -1,47 +1,61 @@
|
||||
# Get spdlog version from include/spdlog/version.h and put it in SPDLOG_VERSION
|
||||
function(spdlog_extract_version)
|
||||
file(READ "${CMAKE_CURRENT_LIST_DIR}/include/spdlog/version.h" file_contents)
|
||||
string(REGEX MATCH "SPDLOG_VER_MAJOR ([0-9]+)" _ "${file_contents}")
|
||||
if(NOT CMAKE_MATCH_COUNT EQUAL 1)
|
||||
message(FATAL_ERROR "Could not extract major version number from spdlog/version.h")
|
||||
endif()
|
||||
set(ver_major ${CMAKE_MATCH_1})
|
||||
|
||||
string(REGEX MATCH "SPDLOG_VER_MINOR ([0-9]+)" _ "${file_contents}")
|
||||
if(NOT CMAKE_MATCH_COUNT EQUAL 1)
|
||||
message(FATAL_ERROR "Could not extract minor version number from spdlog/version.h")
|
||||
endif()
|
||||
|
||||
set(ver_minor ${CMAKE_MATCH_1})
|
||||
string(REGEX MATCH "SPDLOG_VER_PATCH ([0-9]+)" _ "${file_contents}")
|
||||
if(NOT CMAKE_MATCH_COUNT EQUAL 1)
|
||||
message(FATAL_ERROR "Could not extract patch version number from spdlog/version.h")
|
||||
endif()
|
||||
set(ver_patch ${CMAKE_MATCH_1})
|
||||
|
||||
set(SPDLOG_VERSION_MAJOR ${ver_major} PARENT_SCOPE)
|
||||
set (SPDLOG_VERSION "${ver_major}.${ver_minor}.${ver_patch}" PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
|
||||
# Turn on warnings on the given target
|
||||
function(spdlog_enable_warnings target_name)
|
||||
target_compile_options(${target_name} PRIVATE
|
||||
$<$<OR:$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>,$<CXX_COMPILER_ID:GNU>>:
|
||||
-Wall -Wextra -Wconversion -pedantic -Wfatal-errors>
|
||||
$<$<CXX_COMPILER_ID:MSVC>:/W4 /WX>)
|
||||
endfunction()
|
||||
|
||||
|
||||
# Enable address sanitizer (gcc/clang only)
|
||||
function(spdlog_enable_sanitizer target_name)
|
||||
if (NOT CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
|
||||
message(FATAL_ERROR "Sanitizer supported only for gcc/clang")
|
||||
endif()
|
||||
message(STATUS "Address sanitizer enabled")
|
||||
target_compile_options(${target_name} PRIVATE -fsanitize=address,undefined)
|
||||
target_compile_options(${target_name} PRIVATE -fno-sanitize=signed-integer-overflow)
|
||||
target_compile_options(${target_name} PRIVATE -fno-sanitize-recover=all)
|
||||
target_compile_options(${target_name} PRIVATE -fno-omit-frame-pointer)
|
||||
target_link_libraries(${target_name} PRIVATE -fsanitize=address,undefined -fuse-ld=gold)
|
||||
endfunction()
|
||||
# Get spdlog version from include/spdlog/version.h and put it in SPDLOG_VERSION
|
||||
function(spdlog_extract_version)
|
||||
file(READ "${CMAKE_CURRENT_LIST_DIR}/include/spdlog/version.h" file_contents)
|
||||
string(REGEX MATCH "SPDLOG_VER_MAJOR ([0-9]+)" _ "${file_contents}")
|
||||
if(NOT CMAKE_MATCH_COUNT EQUAL 1)
|
||||
message(FATAL_ERROR "Could not extract major version number from spdlog/version.h")
|
||||
endif()
|
||||
set(ver_major ${CMAKE_MATCH_1})
|
||||
|
||||
string(REGEX MATCH "SPDLOG_VER_MINOR ([0-9]+)" _ "${file_contents}")
|
||||
if(NOT CMAKE_MATCH_COUNT EQUAL 1)
|
||||
message(FATAL_ERROR "Could not extract minor version number from spdlog/version.h")
|
||||
endif()
|
||||
|
||||
set(ver_minor ${CMAKE_MATCH_1})
|
||||
string(REGEX MATCH "SPDLOG_VER_PATCH ([0-9]+)" _ "${file_contents}")
|
||||
if(NOT CMAKE_MATCH_COUNT EQUAL 1)
|
||||
message(FATAL_ERROR "Could not extract patch version number from spdlog/version.h")
|
||||
endif()
|
||||
set(ver_patch ${CMAKE_MATCH_1})
|
||||
|
||||
set(SPDLOG_VERSION_MAJOR ${ver_major} PARENT_SCOPE)
|
||||
set(SPDLOG_VERSION_MINOR ${ver_minor} PARENT_SCOPE)
|
||||
set(SPDLOG_VERSION_PATCH ${ver_patch} PARENT_SCOPE)
|
||||
set(SPDLOG_VERSION "${ver_major}.${ver_minor}.${ver_patch}" PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
# Turn on warnings on the given target
|
||||
function(spdlog_enable_warnings target_name)
|
||||
if(SPDLOG_BUILD_WARNINGS)
|
||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
|
||||
list(APPEND MSVC_OPTIONS "/W3")
|
||||
if(MSVC_VERSION GREATER 1900) # Allow non fatal security warnings for msvc 2015
|
||||
list(APPEND MSVC_OPTIONS "/WX")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
target_compile_options(
|
||||
${target_name}
|
||||
PRIVATE $<$<OR:$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>,$<CXX_COMPILER_ID:GNU>>:
|
||||
-Wall
|
||||
-Wextra
|
||||
-Wconversion
|
||||
-pedantic
|
||||
-Wfatal-errors>
|
||||
$<$<CXX_COMPILER_ID:MSVC>:${MSVC_OPTIONS}>)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# Enable address sanitizer (gcc/clang only)
|
||||
function(spdlog_enable_sanitizer target_name)
|
||||
if(NOT CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
|
||||
message(FATAL_ERROR "Sanitizer supported only for gcc/clang")
|
||||
endif()
|
||||
message(STATUS "Address sanitizer enabled")
|
||||
target_compile_options(${target_name} PRIVATE -fsanitize=address,undefined)
|
||||
target_compile_options(${target_name} PRIVATE -fno-sanitize=signed-integer-overflow)
|
||||
target_compile_options(${target_name} PRIVATE -fno-sanitize-recover=all)
|
||||
target_compile_options(${target_name} PRIVATE -fno-omit-frame-pointer)
|
||||
target_link_libraries(${target_name} PRIVATE -fsanitize=address,undefined -fuse-ld=gold)
|
||||
endfunction()
|
||||
|
42
cmake/version.rc.in
Normal file
42
cmake/version.rc.in
Normal file
@@ -0,0 +1,42 @@
|
||||
#define APSTUDIO_READONLY_SYMBOLS
|
||||
#include "winres.h"
|
||||
#undef APSTUDIO_READONLY_SYMBOLS
|
||||
|
||||
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
|
||||
|
||||
|
||||
VS_VERSION_INFO VERSIONINFO
|
||||
FILEVERSION @SPDLOG_VERSION_MAJOR@,@SPDLOG_VERSION_MINOR@,@SPDLOG_VERSION_PATCH@,0
|
||||
PRODUCTVERSION @SPDLOG_VERSION_MAJOR@,@SPDLOG_VERSION_MINOR@,@SPDLOG_VERSION_PATCH@,0
|
||||
FILEFLAGSMASK 0x3fL
|
||||
#ifdef _DEBUG
|
||||
FILEFLAGS 0x1L
|
||||
#else
|
||||
FILEFLAGS 0x0L
|
||||
#endif
|
||||
FILEOS 0x40004L
|
||||
FILETYPE 0x2L
|
||||
FILESUBTYPE 0x0L
|
||||
BEGIN
|
||||
BLOCK "StringFileInfo"
|
||||
BEGIN
|
||||
BLOCK "040904b0"
|
||||
BEGIN
|
||||
VALUE "FileDescription", "spdlog dll\0"
|
||||
VALUE "FileVersion", "@SPDLOG_VERSION@.0\0"
|
||||
VALUE "InternalName", "spdlog.dll\0"
|
||||
VALUE "LegalCopyright", "Copyright (C) spdlog\0"
|
||||
VALUE "ProductName", "spdlog\0"
|
||||
VALUE "ProductVersion", "@SPDLOG_VERSION@.0\0"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
BEGIN
|
||||
VALUE "Translation", 0x409, 1200
|
||||
END
|
||||
END
|
||||
|
||||
|
||||
|
||||
|
||||
|
@@ -1,7 +1,6 @@
|
||||
# Copyright(c) 2019 spdlog authors
|
||||
# Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
# Copyright(c) 2019 spdlog authors Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
cmake_minimum_required(VERSION 3.1)
|
||||
cmake_minimum_required(VERSION 3.2)
|
||||
project(spdlog_examples CXX)
|
||||
|
||||
if(NOT TARGET spdlog)
|
||||
@@ -9,21 +8,16 @@ if(NOT TARGET spdlog)
|
||||
find_package(spdlog REQUIRED)
|
||||
endif()
|
||||
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Example of using pre-compiled library
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
add_executable(example example.cpp)
|
||||
spdlog_enable_warnings(example)
|
||||
target_link_libraries(example PRIVATE spdlog::spdlog)
|
||||
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
# Example of using header-only library
|
||||
#---------------------------------------------------------------------------------------
|
||||
# ---------------------------------------------------------------------------------------
|
||||
if(SPDLOG_BUILD_EXAMPLE_HO)
|
||||
add_executable(example_header_only example.cpp)
|
||||
spdlog_enable_warnings(example_header_only)
|
||||
target_link_libraries(example_header_only PRIVATE spdlog::spdlog_header_only)
|
||||
endif()
|
||||
|
||||
# Create logs directory
|
||||
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/logs")
|
||||
|
@@ -6,6 +6,7 @@
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
void load_levels_example();
|
||||
void stdout_logger_example();
|
||||
void basic_example();
|
||||
void rotating_example();
|
||||
@@ -17,12 +18,18 @@ void multi_sink_example();
|
||||
void user_defined_example();
|
||||
void err_handler_example();
|
||||
void syslog_example();
|
||||
void custom_flags_example();
|
||||
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "spdlog/cfg/env.h" // for loading levels from the environment variable
|
||||
|
||||
int main(int, char *[])
|
||||
{
|
||||
// Log levels can be loaded from argv/env using "SPDLOG_LEVEL"
|
||||
load_levels_example();
|
||||
|
||||
spdlog::info("Welcome to spdlog version {}.{}.{} !", SPDLOG_VER_MAJOR, SPDLOG_VER_MINOR, SPDLOG_VER_PATCH);
|
||||
|
||||
spdlog::warn("Easy padding in numbers like {:08d}", 12);
|
||||
spdlog::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
|
||||
spdlog::info("Support for floats {:03.2f}", 1.23456);
|
||||
@@ -64,6 +71,7 @@ int main(int, char *[])
|
||||
user_defined_example();
|
||||
err_handler_example();
|
||||
trace_example();
|
||||
custom_flags_example();
|
||||
|
||||
// Flush all *registered* loggers using a worker thread every 3 seconds.
|
||||
// note: registered loggers *must* be thread safe for this to work correctly!
|
||||
@@ -116,6 +124,18 @@ void daily_example()
|
||||
auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
|
||||
}
|
||||
|
||||
#include "spdlog/cfg/env.h"
|
||||
void load_levels_example()
|
||||
{
|
||||
// Set the log level to "info" and mylogger to to "trace":
|
||||
// SPDLOG_LEVEL=info,mylogger=trace && ./example
|
||||
spdlog::cfg::load_env_levels();
|
||||
// or from command line:
|
||||
// ./example SPDLOG_LEVEL=info,mylogger=trace
|
||||
// #include "spdlog/cfg/argv.h" // for loading levels from argv
|
||||
// spdlog::cfg::load_argv_levels(args, argv);
|
||||
}
|
||||
|
||||
#include "spdlog/async.h"
|
||||
void async_example()
|
||||
{
|
||||
@@ -143,7 +163,7 @@ void async_example()
|
||||
#include "spdlog/fmt/bin_to_hex.h"
|
||||
void binary_example()
|
||||
{
|
||||
std::vector<char> buf;
|
||||
std::vector<char> buf(80);
|
||||
for (int i = 0; i < 80; i++)
|
||||
{
|
||||
buf.push_back(static_cast<char>(i & 0xff));
|
||||
@@ -154,6 +174,8 @@ void binary_example()
|
||||
// logger->info("uppercase: {:X}", spdlog::to_hex(buf));
|
||||
// logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf));
|
||||
// logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf));
|
||||
// logger->info("hexdump style: {:a}", spdlog::to_hex(buf));
|
||||
// logger->info("hexdump style, 20 chars per line {:a}", spdlog::to_hex(buf, 20));
|
||||
}
|
||||
|
||||
// Compile time log levels.
|
||||
@@ -230,5 +252,31 @@ void android_example()
|
||||
auto android_logger = spdlog::android_logger_mt("android", tag);
|
||||
android_logger->critical("Use \"adb shell logcat\" to view this message.");
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
// Log patterns can contain custom flags.
|
||||
// this will add custom flag '%*' which will be bound to a <my_formatter_flag> instance
|
||||
#include "spdlog/pattern_formatter.h"
|
||||
class my_formatter_flag : public spdlog::custom_flag_formatter
|
||||
{
|
||||
public:
|
||||
void format(const spdlog::details::log_msg &, const std::tm &, spdlog::memory_buf_t &dest) override
|
||||
{
|
||||
std::string some_txt = "custom-flag";
|
||||
dest.append(some_txt.data(), some_txt.data() + some_txt.size());
|
||||
}
|
||||
|
||||
std::unique_ptr<custom_flag_formatter> clone() const override
|
||||
{
|
||||
return spdlog::details::make_unique<my_formatter_flag>();
|
||||
}
|
||||
};
|
||||
|
||||
void custom_flags_example()
|
||||
{
|
||||
|
||||
using spdlog::details::make_unique; // for pre c++14
|
||||
auto formatter = make_unique<spdlog::pattern_formatter>();
|
||||
formatter->add_flag<my_formatter_flag>('*').set_pattern("[%n] [%*] [%^%l%$] %v");
|
||||
spdlog::set_formatter(std::move(formatter));
|
||||
}
|
||||
|
@@ -1,5 +0,0 @@
|
||||
executable('example', 'example.cpp', dependencies: spdlog_dep)
|
||||
executable('example_header_only', 'example.cpp', dependencies: spdlog_headeronly_dep)
|
||||
run_command(find_program('mkdir'), meson.current_build_dir() + '/logs')
|
||||
|
||||
|
@@ -6,7 +6,7 @@
|
||||
//
|
||||
// Async logging using global thread pool
|
||||
// All loggers created here share same global thread pool.
|
||||
// Each log message is pushed to a queue along withe a shared pointer to the
|
||||
// Each log message is pushed to a queue along with a shared pointer to the
|
||||
// logger.
|
||||
// If a logger deleted while having pending messages in the queue, it's actual
|
||||
// destruction will defer
|
||||
@@ -14,9 +14,9 @@
|
||||
// This is because each message in the queue holds a shared_ptr to the
|
||||
// originating logger.
|
||||
|
||||
#include "spdlog/async_logger.h"
|
||||
#include "spdlog/details/registry.h"
|
||||
#include "spdlog/details/thread_pool.h"
|
||||
#include <spdlog/async_logger.h>
|
||||
#include <spdlog/details/registry.h>
|
||||
#include <spdlog/details/thread_pool.h>
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
|
@@ -4,11 +4,11 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/async_logger.h"
|
||||
#include <spdlog/async_logger.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/sinks/sink.h"
|
||||
#include "spdlog/details/thread_pool.h"
|
||||
#include <spdlog/sinks/sink.h>
|
||||
#include <spdlog/details/thread_pool.h>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
@@ -32,7 +32,7 @@ SPDLOG_INLINE void spdlog::async_logger::sink_it_(const details::log_msg &msg)
|
||||
}
|
||||
else
|
||||
{
|
||||
SPDLOG_THROW(spdlog_ex("async log: thread pool doesn't exist anymore"));
|
||||
throw_spdlog_ex("async log: thread pool doesn't exist anymore");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ SPDLOG_INLINE void spdlog::async_logger::flush_()
|
||||
}
|
||||
else
|
||||
{
|
||||
SPDLOG_THROW(spdlog_ex("async flush: thread pool doesn't exist anymore"));
|
||||
throw_spdlog_ex("async flush: thread pool doesn't exist anymore");
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -14,7 +14,7 @@
|
||||
// Upon destruction, logs all remaining messages in the queue before
|
||||
// destructing..
|
||||
|
||||
#include "spdlog/logger.h"
|
||||
#include <spdlog/logger.h>
|
||||
|
||||
namespace spdlog {
|
||||
|
||||
@@ -30,7 +30,7 @@ namespace details {
|
||||
class thread_pool;
|
||||
}
|
||||
|
||||
class async_logger final : public std::enable_shared_from_this<async_logger>, public logger
|
||||
class SPDLOG_API async_logger final : public std::enable_shared_from_this<async_logger>, public logger
|
||||
{
|
||||
friend class details::thread_pool;
|
||||
|
||||
|
45
include/spdlog/cfg/argv.h
Normal file
45
include/spdlog/cfg/argv.h
Normal file
@@ -0,0 +1,45 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
#include <spdlog/cfg/helpers.h>
|
||||
#include <spdlog/details/registry.h>
|
||||
|
||||
//
|
||||
// Init log levels using each argv entry that starts with "SPDLOG_LEVEL="
|
||||
//
|
||||
// set all loggers to debug level:
|
||||
// example.exe "SPDLOG_LEVEL=debug"
|
||||
|
||||
// set logger1 to trace level
|
||||
// example.exe "SPDLOG_LEVEL=logger1=trace"
|
||||
|
||||
// turn off all logging except for logger1 and logger2:
|
||||
// example.exe "SPDLOG_LEVEL=off,logger1=debug,logger2=info"
|
||||
|
||||
namespace spdlog {
|
||||
namespace cfg {
|
||||
|
||||
// search for SPDLOG_LEVEL= in the args and use it to init the levels
|
||||
void load_argv_levels(int argc, const char **argv)
|
||||
{
|
||||
const std::string spdlog_level_prefix = "SPDLOG_LEVEL=";
|
||||
for (int i = 1; i < argc; i++)
|
||||
{
|
||||
std::string arg = argv[i];
|
||||
if (arg.find(spdlog_level_prefix) == 0)
|
||||
{
|
||||
auto levels_string = arg.substr(spdlog_level_prefix.size());
|
||||
auto levels = helpers::extract_levels(levels_string);
|
||||
details::registry::instance().update_levels(std::move(levels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void load_argv_levels(int argc, char **argv)
|
||||
{
|
||||
load_argv_levels(argc, const_cast<const char **>(argv));
|
||||
}
|
||||
|
||||
} // namespace cfg
|
||||
} // namespace spdlog
|
36
include/spdlog/cfg/env.h
Normal file
36
include/spdlog/cfg/env.h
Normal file
@@ -0,0 +1,36 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
#include <spdlog/cfg/helpers.h>
|
||||
#include <spdlog/details/registry.h>
|
||||
#include <spdlog/details/os.h>
|
||||
|
||||
//
|
||||
// Init levels and patterns from env variables SPDLOG_LEVEL
|
||||
// Inspired from Rust's "env_logger" crate (https://crates.io/crates/env_logger).
|
||||
// Note - fallback to "info" level on unrecognized levels
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// set global level to debug:
|
||||
// export SPDLOG_LEVEL=debug
|
||||
//
|
||||
// turn off all logging except for logger1:
|
||||
// export SPDLOG_LEVEL="off,logger1=debug"
|
||||
//
|
||||
|
||||
// turn off all logging except for logger1 and logger2:
|
||||
// export SPDLOG_LEVEL="off,logger1=debug,logger2=info"
|
||||
|
||||
namespace spdlog {
|
||||
namespace cfg {
|
||||
void load_env_levels()
|
||||
{
|
||||
auto env_val = details::os::getenv("SPDLOG_LEVEL");
|
||||
auto levels = helpers::extract_levels(env_val);
|
||||
details::registry::instance().update_levels(std::move(levels));
|
||||
}
|
||||
|
||||
} // namespace cfg
|
||||
} // namespace spdlog
|
103
include/spdlog/cfg/helpers-inl.h
Normal file
103
include/spdlog/cfg/helpers-inl.h
Normal file
@@ -0,0 +1,103 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include <spdlog/cfg/helpers.h>
|
||||
#endif
|
||||
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <spdlog/details/os.h>
|
||||
#include <spdlog/details/registry.h>
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <sstream>
|
||||
|
||||
namespace spdlog {
|
||||
namespace cfg {
|
||||
namespace helpers {
|
||||
|
||||
// inplace convert to lowercase
|
||||
inline std::string &to_lower_(std::string &str)
|
||||
{
|
||||
std::transform(
|
||||
str.begin(), str.end(), str.begin(), [](char ch) { return static_cast<char>((ch >= 'A' && ch <= 'Z') ? ch + ('a' - 'A') : ch); });
|
||||
return str;
|
||||
}
|
||||
|
||||
// inplace trim spaces
|
||||
inline std::string &trim_(std::string &str)
|
||||
{
|
||||
const char *spaces = " \n\r\t";
|
||||
str.erase(str.find_last_not_of(spaces) + 1);
|
||||
str.erase(0, str.find_first_not_of(spaces));
|
||||
return str;
|
||||
}
|
||||
|
||||
// return (name,value) trimmed pair from given "name=value" string.
|
||||
// return empty string on missing parts
|
||||
// "key=val" => ("key", "val")
|
||||
// " key = val " => ("key", "val")
|
||||
// "key=" => ("key", "")
|
||||
// "val" => ("", "val")
|
||||
|
||||
inline std::pair<std::string, std::string> extract_kv_(char sep, const std::string &str)
|
||||
{
|
||||
auto n = str.find(sep);
|
||||
std::string k, v;
|
||||
if (n == std::string::npos)
|
||||
{
|
||||
v = str;
|
||||
}
|
||||
else
|
||||
{
|
||||
k = str.substr(0, n);
|
||||
v = str.substr(n + 1);
|
||||
}
|
||||
return std::make_pair(trim_(k), trim_(v));
|
||||
}
|
||||
|
||||
// return vector of key/value pairs from sequence of "K1=V1,K2=V2,.."
|
||||
// "a=AAA,b=BBB,c=CCC,.." => {("a","AAA"),("b","BBB"),("c", "CCC"),...}
|
||||
inline std::unordered_map<std::string, std::string> extract_key_vals_(const std::string &str)
|
||||
{
|
||||
std::string token;
|
||||
std::istringstream token_stream(str);
|
||||
std::unordered_map<std::string, std::string> rv{};
|
||||
while (std::getline(token_stream, token, ','))
|
||||
{
|
||||
if (token.empty())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
auto kv = extract_kv_('=', token);
|
||||
rv[kv.first] = kv.second;
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE log_levels extract_levels(const std::string &input)
|
||||
{
|
||||
auto key_vals = extract_key_vals_(input);
|
||||
log_levels rv;
|
||||
|
||||
for (auto &name_level : key_vals)
|
||||
{
|
||||
auto &logger_name = name_level.first;
|
||||
auto level_name = to_lower_(name_level.second);
|
||||
auto level = level::from_str(level_name);
|
||||
// fallback to "info" if unrecognized level name
|
||||
if (level == level::off && level_name != "off")
|
||||
{
|
||||
level = level::info;
|
||||
}
|
||||
rv.set(logger_name, level);
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
} // namespace helpers
|
||||
} // namespace cfg
|
||||
} // namespace spdlog
|
28
include/spdlog/cfg/helpers.h
Normal file
28
include/spdlog/cfg/helpers.h
Normal file
@@ -0,0 +1,28 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <spdlog/cfg/log_levels.h>
|
||||
|
||||
namespace spdlog {
|
||||
namespace cfg {
|
||||
namespace helpers {
|
||||
//
|
||||
// Init levels from given string
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// set global level to debug: "debug"
|
||||
// turn off all logging except for logger1: "off,logger1=debug"
|
||||
// turn off all logging except for logger1 and logger2: "off,logger1=debug,logger2=info"
|
||||
//
|
||||
SPDLOG_API log_levels extract_levels(const std::string &txt);
|
||||
} // namespace helpers
|
||||
|
||||
} // namespace cfg
|
||||
} // namespace spdlog
|
||||
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
#include "helpers-inl.h"
|
||||
#endif // SPDLOG_HEADER_ONLY
|
47
include/spdlog/cfg/log_levels.h
Normal file
47
include/spdlog/cfg/log_levels.h
Normal file
@@ -0,0 +1,47 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <spdlog/common.h>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace spdlog {
|
||||
namespace cfg {
|
||||
class log_levels
|
||||
{
|
||||
std::unordered_map<std::string, spdlog::level::level_enum> levels_;
|
||||
spdlog::level::level_enum default_level_ = level::info;
|
||||
|
||||
public:
|
||||
void set(const std::string &logger_name, level::level_enum lvl)
|
||||
{
|
||||
if (logger_name.empty())
|
||||
{
|
||||
default_level_ = lvl;
|
||||
}
|
||||
else
|
||||
{
|
||||
levels_[logger_name] = lvl;
|
||||
}
|
||||
}
|
||||
|
||||
void set_default(level::level_enum lvl)
|
||||
{
|
||||
default_level_ = lvl;
|
||||
}
|
||||
|
||||
level::level_enum get(const std::string &logger_name)
|
||||
{
|
||||
auto it = levels_.find(logger_name);
|
||||
return it != levels_.end() ? it->second : default_level_;
|
||||
}
|
||||
|
||||
level::level_enum default_level()
|
||||
{
|
||||
return default_level_;
|
||||
}
|
||||
};
|
||||
} // namespace cfg
|
||||
} // namespace spdlog
|
@@ -4,7 +4,7 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/common.h"
|
||||
#include <spdlog/common.h>
|
||||
#endif
|
||||
|
||||
namespace spdlog {
|
||||
@@ -34,6 +34,15 @@ SPDLOG_INLINE spdlog::level::level_enum from_str(const std::string &name) SPDLOG
|
||||
}
|
||||
level++;
|
||||
}
|
||||
// check also for "warn" and "err" before giving up..
|
||||
if (name == "warn")
|
||||
{
|
||||
return level::warn;
|
||||
}
|
||||
if (name == "err")
|
||||
{
|
||||
return level::err;
|
||||
}
|
||||
return level::off;
|
||||
}
|
||||
} // namespace level
|
||||
@@ -54,4 +63,14 @@ SPDLOG_INLINE const char *spdlog_ex::what() const SPDLOG_NOEXCEPT
|
||||
return msg_.c_str();
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void throw_spdlog_ex(const std::string &msg, int last_errno)
|
||||
{
|
||||
SPDLOG_THROW(spdlog_ex(msg, last_errno));
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void throw_spdlog_ex(std::string msg)
|
||||
{
|
||||
SPDLOG_THROW(spdlog_ex(std::move(msg)));
|
||||
}
|
||||
|
||||
} // namespace spdlog
|
||||
|
@@ -3,8 +3,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/tweakme.h"
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
#include <spdlog/tweakme.h>
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
@@ -15,27 +15,25 @@
|
||||
#include <type_traits>
|
||||
#include <functional>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX // prevent windows redefining min/max
|
||||
#endif
|
||||
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
|
||||
#include <windows.h>
|
||||
#endif //_WIN32
|
||||
|
||||
#ifdef SPDLOG_COMPILED_LIB
|
||||
#undef SPDLOG_HEADER_ONLY
|
||||
#define SPDLOG_INLINE
|
||||
#if defined(_WIN32) && defined(SPDLOG_SHARED_LIB)
|
||||
#ifdef spdlog_EXPORTS
|
||||
#define SPDLOG_API __declspec(dllexport)
|
||||
#else
|
||||
#define SPDLOG_API __declspec(dllimport)
|
||||
#endif
|
||||
#else // !defined(_WIN32) || !defined(SPDLOG_SHARED_LIB)
|
||||
#define SPDLOG_API
|
||||
#endif
|
||||
#define SPDLOG_INLINE
|
||||
#else // !defined(SPDLOG_COMPILED_LIB)
|
||||
#define SPDLOG_API
|
||||
#define SPDLOG_HEADER_ONLY
|
||||
#define SPDLOG_INLINE inline
|
||||
#endif
|
||||
#endif // #ifdef SPDLOG_COMPILED_LIB
|
||||
|
||||
#include "spdlog/fmt/fmt.h"
|
||||
#include <spdlog/fmt/fmt.h>
|
||||
|
||||
// visual studio upto 2013 does not support noexcept nor constexpr
|
||||
#if defined(_MSC_VER) && (_MSC_VER < 1900)
|
||||
@@ -62,7 +60,7 @@
|
||||
#endif
|
||||
|
||||
#ifndef SPDLOG_FUNCTION
|
||||
#define SPDLOG_FUNCTION __FUNCTION__
|
||||
#define SPDLOG_FUNCTION static_cast<const char *>(__FUNCTION__)
|
||||
#endif
|
||||
|
||||
#ifdef SPDLOG_NO_EXCEPTIONS
|
||||
@@ -101,14 +99,13 @@ using sink_ptr = std::shared_ptr<sinks::sink>;
|
||||
using sinks_init_list = std::initializer_list<sink_ptr>;
|
||||
using err_handler = std::function<void(const std::string &err_msg)>;
|
||||
using string_view_t = fmt::basic_string_view<char>;
|
||||
using wstring_view_t = fmt::basic_string_view<wchar_t>;
|
||||
using memory_buf_t = fmt::basic_memory_buffer<char, 250>;
|
||||
|
||||
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
|
||||
#ifndef _WIN32
|
||||
#error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows
|
||||
#else
|
||||
using wstring_view_t = fmt::basic_string_view<wchar_t>;
|
||||
|
||||
template<typename T>
|
||||
struct is_convertible_to_wstring_view : std::is_convertible<T, wstring_view_t>
|
||||
{};
|
||||
@@ -148,6 +145,7 @@ enum level_enum
|
||||
err = SPDLOG_LEVEL_ERROR,
|
||||
critical = SPDLOG_LEVEL_CRITICAL,
|
||||
off = SPDLOG_LEVEL_OFF,
|
||||
n_levels
|
||||
};
|
||||
|
||||
#if !defined(SPDLOG_LEVEL_NAMES)
|
||||
@@ -165,9 +163,9 @@ enum level_enum
|
||||
}
|
||||
#endif
|
||||
|
||||
string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT;
|
||||
const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT;
|
||||
spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT;
|
||||
|
||||
using level_hasher = std::hash<int>;
|
||||
} // namespace level
|
||||
@@ -195,7 +193,7 @@ enum class pattern_time_type
|
||||
//
|
||||
// Log exception
|
||||
//
|
||||
class spdlog_ex : public std::exception
|
||||
class SPDLOG_API spdlog_ex : public std::exception
|
||||
{
|
||||
public:
|
||||
explicit spdlog_ex(std::string msg);
|
||||
@@ -206,6 +204,9 @@ private:
|
||||
std::string msg_;
|
||||
};
|
||||
|
||||
SPDLOG_API void throw_spdlog_ex(const std::string &msg, int last_errno);
|
||||
SPDLOG_API void throw_spdlog_ex(std::string msg);
|
||||
|
||||
struct source_loc
|
||||
{
|
||||
SPDLOG_CONSTEXPR source_loc() = default;
|
||||
@@ -238,7 +239,6 @@ std::unique_ptr<T> make_unique(Args &&... args)
|
||||
}
|
||||
#endif
|
||||
} // namespace details
|
||||
|
||||
} // namespace spdlog
|
||||
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
|
@@ -4,7 +4,7 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/details/backtracer.h"
|
||||
#include <spdlog/details/backtracer.h>
|
||||
#endif
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
@@ -26,7 +26,7 @@ SPDLOG_INLINE backtracer &backtracer::operator=(backtracer other)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
enabled_ = other.enabled();
|
||||
messages_ = other.messages_;
|
||||
messages_ = std::move(other.messages_);
|
||||
return *this;
|
||||
}
|
||||
|
||||
@@ -48,11 +48,6 @@ SPDLOG_INLINE bool backtracer::enabled() const
|
||||
return enabled_.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE backtracer::operator bool() const
|
||||
{
|
||||
return enabled();
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void backtracer::push_back(const log_msg &msg)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock{mutex_};
|
||||
|
@@ -3,8 +3,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/details/log_msg_buffer.h"
|
||||
#include "spdlog/details/circular_q.h"
|
||||
#include <spdlog/details/log_msg_buffer.h>
|
||||
#include <spdlog/details/circular_q.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
class backtracer
|
||||
class SPDLOG_API backtracer
|
||||
{
|
||||
mutable std::mutex mutex_;
|
||||
std::atomic<bool> enabled_{false};
|
||||
@@ -31,7 +31,6 @@ public:
|
||||
void enable(size_t size);
|
||||
void disable();
|
||||
bool enabled() const;
|
||||
explicit operator bool() const;
|
||||
void push_back(const log_msg &msg);
|
||||
|
||||
// pop all items in the q and apply the given fun on each of them.
|
||||
|
@@ -1,10 +1,11 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
// cirucal q view of std::vector.
|
||||
// circular q view of std::vector.
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
#include <cassert>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
@@ -72,6 +73,27 @@ public:
|
||||
return v_[head_];
|
||||
}
|
||||
|
||||
// Return number of elements actually stored
|
||||
size_t size() const
|
||||
{
|
||||
if (tail_ >= head_)
|
||||
{
|
||||
return tail_ - head_;
|
||||
}
|
||||
else
|
||||
{
|
||||
return max_items_ - (head_ - tail_);
|
||||
}
|
||||
}
|
||||
|
||||
// Return const reference to item by index.
|
||||
// If index is out of range 0…size()-1, the behavior is undefined.
|
||||
const T &at(size_t i) const
|
||||
{
|
||||
assert(i < size());
|
||||
return v_[(head_ + i) % max_items_];
|
||||
}
|
||||
|
||||
// Pop item from front.
|
||||
// If there are no elements in the container, the behavior is undefined.
|
||||
void pop_front()
|
||||
|
@@ -3,7 +3,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <mutex>
|
||||
|
||||
namespace spdlog {
|
||||
|
@@ -4,11 +4,11 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/details/file_helper.h"
|
||||
#include <spdlog/details/file_helper.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/details/os.h"
|
||||
#include "spdlog/common.h"
|
||||
#include <spdlog/details/os.h>
|
||||
#include <spdlog/common.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
@@ -28,28 +28,31 @@ SPDLOG_INLINE file_helper::~file_helper()
|
||||
SPDLOG_INLINE void file_helper::open(const filename_t &fname, bool truncate)
|
||||
{
|
||||
close();
|
||||
filename_ = fname;
|
||||
auto *mode = truncate ? SPDLOG_FILENAME_T("wb") : SPDLOG_FILENAME_T("ab");
|
||||
_filename = fname;
|
||||
for (int tries = 0; tries < open_tries; ++tries)
|
||||
|
||||
for (int tries = 0; tries < open_tries_; ++tries)
|
||||
{
|
||||
// create containing folder if not exists already.
|
||||
os::create_dir(os::dir_name(fname));
|
||||
if (!os::fopen_s(&fd_, fname, mode))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
details::os::sleep_for_millis(open_interval);
|
||||
details::os::sleep_for_millis(open_interval_);
|
||||
}
|
||||
|
||||
SPDLOG_THROW(spdlog_ex("Failed opening file " + os::filename_to_str(_filename) + " for writing", errno));
|
||||
throw_spdlog_ex("Failed opening file " + os::filename_to_str(filename_) + " for writing", errno);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void file_helper::reopen(bool truncate)
|
||||
{
|
||||
if (_filename.empty())
|
||||
if (filename_.empty())
|
||||
{
|
||||
SPDLOG_THROW(spdlog_ex("Failed re opening file - was not opened before"));
|
||||
throw_spdlog_ex("Failed re opening file - was not opened before");
|
||||
}
|
||||
open(_filename, truncate);
|
||||
this->open(filename_, truncate);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void file_helper::flush()
|
||||
@@ -72,7 +75,7 @@ SPDLOG_INLINE void file_helper::write(const memory_buf_t &buf)
|
||||
auto data = buf.data();
|
||||
if (std::fwrite(data, 1, msg_size, fd_) != msg_size)
|
||||
{
|
||||
SPDLOG_THROW(spdlog_ex("Failed writing to file " + os::filename_to_str(_filename), errno));
|
||||
throw_spdlog_ex("Failed writing to file " + os::filename_to_str(filename_), errno);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,19 +83,14 @@ SPDLOG_INLINE size_t file_helper::size() const
|
||||
{
|
||||
if (fd_ == nullptr)
|
||||
{
|
||||
SPDLOG_THROW(spdlog_ex("Cannot use size() on closed file " + os::filename_to_str(_filename)));
|
||||
throw_spdlog_ex("Cannot use size() on closed file " + os::filename_to_str(filename_));
|
||||
}
|
||||
return os::filesize(fd_);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE const filename_t &file_helper::filename() const
|
||||
{
|
||||
return _filename;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE bool file_helper::file_exists(const filename_t &fname)
|
||||
{
|
||||
return os::file_exists(fname);
|
||||
return filename_;
|
||||
}
|
||||
|
||||
//
|
||||
@@ -119,7 +117,7 @@ SPDLOG_INLINE std::tuple<filename_t, filename_t> file_helper::split_by_extension
|
||||
return std::make_tuple(fname, filename_t());
|
||||
}
|
||||
|
||||
// treat casese like "/etc/rc.d/somelogfile or "/abc/.hiddenfile"
|
||||
// treat cases like "/etc/rc.d/somelogfile or "/abc/.hiddenfile"
|
||||
auto folder_index = fname.rfind(details::os::folder_sep);
|
||||
if (folder_index != filename_t::npos && folder_index >= ext_index - 1)
|
||||
{
|
||||
@@ -129,5 +127,6 @@ SPDLOG_INLINE std::tuple<filename_t, filename_t> file_helper::split_by_extension
|
||||
// finally - return a valid base and extension tuple
|
||||
return std::make_tuple(fname.substr(0, ext_index), fname.substr(ext_index));
|
||||
}
|
||||
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
||||
|
@@ -3,7 +3,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/common.h"
|
||||
#include <spdlog/common.h>
|
||||
#include <tuple>
|
||||
|
||||
namespace spdlog {
|
||||
@@ -13,7 +13,7 @@ namespace details {
|
||||
// When failing to open a file, retry several times(5) with a delay interval(10 ms).
|
||||
// Throw spdlog_ex exception on errors.
|
||||
|
||||
class file_helper
|
||||
class SPDLOG_API file_helper
|
||||
{
|
||||
public:
|
||||
explicit file_helper() = default;
|
||||
@@ -29,7 +29,6 @@ public:
|
||||
void write(const memory_buf_t &buf);
|
||||
size_t size() const;
|
||||
const filename_t &filename() const;
|
||||
static bool file_exists(const filename_t &fname);
|
||||
|
||||
//
|
||||
// return file path and its extension:
|
||||
@@ -47,10 +46,10 @@ public:
|
||||
static std::tuple<filename_t, filename_t> split_by_extension(const filename_t &fname);
|
||||
|
||||
private:
|
||||
const int open_tries = 5;
|
||||
const int open_interval = 10;
|
||||
const int open_tries_ = 5;
|
||||
const int open_interval_ = 10;
|
||||
std::FILE *fd_{nullptr};
|
||||
filename_t _filename;
|
||||
filename_t filename_;
|
||||
};
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
||||
|
@@ -4,8 +4,8 @@
|
||||
|
||||
#include <chrono>
|
||||
#include <type_traits>
|
||||
#include "spdlog/fmt/fmt.h"
|
||||
#include "spdlog/common.h"
|
||||
#include <spdlog/fmt/fmt.h>
|
||||
#include <spdlog/common.h>
|
||||
|
||||
// Some fmt helpers to efficiently format and pad ints and strings
|
||||
namespace spdlog {
|
||||
@@ -20,10 +20,7 @@ inline spdlog::string_view_t to_string_view(const memory_buf_t &buf) SPDLOG_NOEX
|
||||
inline void append_string_view(spdlog::string_view_t view, memory_buf_t &dest)
|
||||
{
|
||||
auto *buf_ptr = view.data();
|
||||
if (buf_ptr != nullptr)
|
||||
{
|
||||
dest.append(buf_ptr, buf_ptr + view.size());
|
||||
}
|
||||
dest.append(buf_ptr, buf_ptr + view.size());
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
@@ -34,29 +31,20 @@ inline void append_int(T n, memory_buf_t &dest)
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
inline unsigned count_digits(T n)
|
||||
inline unsigned int count_digits(T n)
|
||||
{
|
||||
using count_type = typename std::conditional<(sizeof(T) > sizeof(uint32_t)), uint64_t, uint32_t>::type;
|
||||
return static_cast<unsigned>(fmt::internal::count_digits(static_cast<count_type>(n)));
|
||||
return static_cast<unsigned int>(fmt::internal::count_digits(static_cast<count_type>(n)));
|
||||
}
|
||||
|
||||
inline void pad2(int n, memory_buf_t &dest)
|
||||
{
|
||||
if (n > 99)
|
||||
{
|
||||
append_int(n, dest);
|
||||
}
|
||||
else if (n > 9) // 10-99
|
||||
if (n >= 0 && n < 100) // 0-99
|
||||
{
|
||||
dest.push_back(static_cast<char>('0' + n / 10));
|
||||
dest.push_back(static_cast<char>('0' + n % 10));
|
||||
}
|
||||
else if (n >= 0) // 0-9
|
||||
{
|
||||
dest.push_back('0');
|
||||
dest.push_back(static_cast<char>('0' + n));
|
||||
}
|
||||
else // negatives (unlikely, but just in case, let fmt deal with it)
|
||||
else // unlikely, but just in case, let fmt deal with it
|
||||
{
|
||||
fmt::format_to(dest, "{:02}", n);
|
||||
}
|
||||
@@ -66,11 +54,9 @@ template<typename T>
|
||||
inline void pad_uint(T n, unsigned int width, memory_buf_t &dest)
|
||||
{
|
||||
static_assert(std::is_unsigned<T>::value, "pad_uint must get unsigned T");
|
||||
auto digits = count_digits(n);
|
||||
if (width > digits)
|
||||
for (auto digits = count_digits(n); digits < width; digits++)
|
||||
{
|
||||
const char *zeroes = "0000000000000000000";
|
||||
dest.append(zeroes, zeroes + width - digits);
|
||||
dest.push_back('0');
|
||||
}
|
||||
append_int(n, dest);
|
||||
}
|
||||
@@ -78,7 +64,18 @@ inline void pad_uint(T n, unsigned int width, memory_buf_t &dest)
|
||||
template<typename T>
|
||||
inline void pad3(T n, memory_buf_t &dest)
|
||||
{
|
||||
pad_uint(n, 3, dest);
|
||||
static_assert(std::is_unsigned<T>::value, "pad3 must get unsigned T");
|
||||
if (n < 1000)
|
||||
{
|
||||
dest.push_back(static_cast<char>(n / 100 + '0'));
|
||||
n = n % 100;
|
||||
dest.push_back(static_cast<char>((n / 10) + '0'));
|
||||
dest.push_back(static_cast<char>((n % 10) + '0'));
|
||||
}
|
||||
else
|
||||
{
|
||||
append_int(n, dest);
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
|
@@ -4,21 +4,19 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/details/log_msg.h"
|
||||
#include <spdlog/details/log_msg.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/details/os.h"
|
||||
#include <spdlog/details/os.h>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
|
||||
SPDLOG_INLINE log_msg::log_msg(spdlog::source_loc loc, string_view_t logger_name, spdlog::level::level_enum lvl, spdlog::string_view_t msg)
|
||||
: logger_name(logger_name)
|
||||
SPDLOG_INLINE log_msg::log_msg(spdlog::log_clock::time_point log_time, spdlog::source_loc loc, string_view_t a_logger_name,
|
||||
spdlog::level::level_enum lvl, spdlog::string_view_t msg)
|
||||
: logger_name(a_logger_name)
|
||||
, level(lvl)
|
||||
#ifndef SPDLOG_NO_DATETIME
|
||||
, time(os::now())
|
||||
#endif
|
||||
|
||||
, time(log_time)
|
||||
#ifndef SPDLOG_NO_THREAD_ID
|
||||
, thread_id(os::thread_id())
|
||||
#endif
|
||||
@@ -26,8 +24,13 @@ SPDLOG_INLINE log_msg::log_msg(spdlog::source_loc loc, string_view_t logger_name
|
||||
, payload(msg)
|
||||
{}
|
||||
|
||||
SPDLOG_INLINE log_msg::log_msg(string_view_t logger_name, spdlog::level::level_enum lvl, spdlog::string_view_t msg)
|
||||
: log_msg(source_loc{}, logger_name, lvl, msg)
|
||||
SPDLOG_INLINE log_msg::log_msg(
|
||||
spdlog::source_loc loc, string_view_t a_logger_name, spdlog::level::level_enum lvl, spdlog::string_view_t msg)
|
||||
: log_msg(os::now(), loc, a_logger_name, lvl, msg)
|
||||
{}
|
||||
|
||||
SPDLOG_INLINE log_msg::log_msg(string_view_t a_logger_name, spdlog::level::level_enum lvl, spdlog::string_view_t msg)
|
||||
: log_msg(os::now(), source_loc{}, a_logger_name, lvl, msg)
|
||||
{}
|
||||
|
||||
} // namespace details
|
||||
|
@@ -3,14 +3,15 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/common.h"
|
||||
#include <spdlog/common.h>
|
||||
#include <string>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
struct log_msg
|
||||
struct SPDLOG_API log_msg
|
||||
{
|
||||
log_msg() = default;
|
||||
log_msg(log_clock::time_point log_time, source_loc loc, string_view_t logger_name, level::level_enum lvl, string_view_t msg);
|
||||
log_msg(source_loc loc, string_view_t logger_name, level::level_enum lvl, string_view_t msg);
|
||||
log_msg(string_view_t logger_name, level::level_enum lvl, string_view_t msg);
|
||||
log_msg(const log_msg &other) = default;
|
||||
|
@@ -4,7 +4,7 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/details/log_msg_buffer.h"
|
||||
#include <spdlog/details/log_msg_buffer.h>
|
||||
#endif
|
||||
|
||||
namespace spdlog {
|
||||
@@ -26,9 +26,7 @@ SPDLOG_INLINE log_msg_buffer::log_msg_buffer(const log_msg_buffer &other)
|
||||
update_string_views();
|
||||
}
|
||||
|
||||
SPDLOG_INLINE log_msg_buffer::log_msg_buffer(log_msg_buffer &&other)
|
||||
: log_msg{std::move(other)}
|
||||
, buffer{std::move(other.buffer)}
|
||||
SPDLOG_INLINE log_msg_buffer::log_msg_buffer(log_msg_buffer &&other) SPDLOG_NOEXCEPT : log_msg{other}, buffer{std::move(other.buffer)}
|
||||
{
|
||||
update_string_views();
|
||||
}
|
||||
@@ -42,9 +40,9 @@ SPDLOG_INLINE log_msg_buffer &log_msg_buffer::operator=(const log_msg_buffer &ot
|
||||
return *this;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE log_msg_buffer &log_msg_buffer::operator=(log_msg_buffer &&other)
|
||||
SPDLOG_INLINE log_msg_buffer &log_msg_buffer::operator=(log_msg_buffer &&other) SPDLOG_NOEXCEPT
|
||||
{
|
||||
log_msg::operator=(std::move(other));
|
||||
log_msg::operator=(other);
|
||||
buffer = std::move(other.buffer);
|
||||
update_string_views();
|
||||
return *this;
|
||||
|
@@ -3,15 +3,15 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/details/log_msg.h"
|
||||
#include <spdlog/details/log_msg.h>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
|
||||
// Extend log_msg with internal buffer to store its payload.
|
||||
// THis is needed since log_msg holds string_views that points to stack data.
|
||||
// This is needed since log_msg holds string_views that points to stack data.
|
||||
|
||||
class log_msg_buffer : public log_msg
|
||||
class SPDLOG_API log_msg_buffer : public log_msg
|
||||
{
|
||||
memory_buf_t buffer;
|
||||
void update_string_views();
|
||||
@@ -20,9 +20,9 @@ public:
|
||||
log_msg_buffer() = default;
|
||||
explicit log_msg_buffer(const log_msg &orig_msg);
|
||||
log_msg_buffer(const log_msg_buffer &other);
|
||||
log_msg_buffer(log_msg_buffer &&other);
|
||||
log_msg_buffer(log_msg_buffer &&other) SPDLOG_NOEXCEPT;
|
||||
log_msg_buffer &operator=(const log_msg_buffer &other);
|
||||
log_msg_buffer &operator=(log_msg_buffer &&other);
|
||||
log_msg_buffer &operator=(log_msg_buffer &&other) SPDLOG_NOEXCEPT;
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
|
@@ -10,7 +10,7 @@
|
||||
// dequeue_for(..) - will block until the queue is not empty or timeout have
|
||||
// passed.
|
||||
|
||||
#include "spdlog/details/circular_q.h"
|
||||
#include <spdlog/details/circular_q.h>
|
||||
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
|
@@ -4,10 +4,10 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/details/os.h"
|
||||
#include <spdlog/details/os.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/common.h"
|
||||
#include <spdlog/common.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
@@ -23,16 +23,9 @@
|
||||
|
||||
#ifdef _WIN32
|
||||
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX // prevent windows redefining min/max
|
||||
#endif
|
||||
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include <io.h> // _get_osfhandle and _isatty support
|
||||
#include <process.h> // _get_pid support
|
||||
#include <windows.h>
|
||||
#include <spdlog/details/windows_include.h>
|
||||
|
||||
#ifdef __MINGW32__
|
||||
#include <share.h>
|
||||
@@ -42,6 +35,8 @@
|
||||
#include <limits>
|
||||
#endif
|
||||
|
||||
#include <direct.h> // for _mkdir/_wmkdir
|
||||
|
||||
#else // unix
|
||||
|
||||
#include <fcntl.h>
|
||||
@@ -91,17 +86,17 @@ SPDLOG_INLINE std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
|
||||
|
||||
#ifdef _WIN32
|
||||
std::tm tm;
|
||||
localtime_s(&tm, &time_tt);
|
||||
::localtime_s(&tm, &time_tt);
|
||||
#else
|
||||
std::tm tm;
|
||||
localtime_r(&time_tt, &tm);
|
||||
::localtime_r(&time_tt, &tm);
|
||||
#endif
|
||||
return tm;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE std::tm localtime() SPDLOG_NOEXCEPT
|
||||
{
|
||||
std::time_t now_t = time(nullptr);
|
||||
std::time_t now_t = ::time(nullptr);
|
||||
return localtime(now_t);
|
||||
}
|
||||
|
||||
@@ -110,64 +105,65 @@ SPDLOG_INLINE std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
|
||||
|
||||
#ifdef _WIN32
|
||||
std::tm tm;
|
||||
gmtime_s(&tm, &time_tt);
|
||||
::gmtime_s(&tm, &time_tt);
|
||||
#else
|
||||
std::tm tm;
|
||||
gmtime_r(&time_tt, &tm);
|
||||
::gmtime_r(&time_tt, &tm);
|
||||
#endif
|
||||
return tm;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE std::tm gmtime() SPDLOG_NOEXCEPT
|
||||
{
|
||||
std::time_t now_t = time(nullptr);
|
||||
std::time_t now_t = ::time(nullptr);
|
||||
return gmtime(now_t);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void prevent_child_fd(FILE *f)
|
||||
{
|
||||
|
||||
#ifdef _WIN32
|
||||
#if !defined(__cplusplus_winrt)
|
||||
auto file_handle = reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(f)));
|
||||
if (!::SetHandleInformation(file_handle, HANDLE_FLAG_INHERIT, 0))
|
||||
SPDLOG_THROW(spdlog_ex("SetHandleInformation failed", errno));
|
||||
#endif
|
||||
#else
|
||||
auto fd = fileno(f);
|
||||
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
|
||||
{
|
||||
SPDLOG_THROW(spdlog_ex("fcntl with FD_CLOEXEC failed", errno));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// fopen_s on non windows for writing
|
||||
SPDLOG_INLINE bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
#ifdef SPDLOG_WCHAR_FILENAMES
|
||||
*fp = _wfsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
|
||||
*fp = ::_wfsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
|
||||
#else
|
||||
*fp = _fsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
|
||||
*fp = ::_fsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
|
||||
#endif
|
||||
#else // unix
|
||||
*fp = fopen((filename.c_str()), mode.c_str());
|
||||
#endif
|
||||
|
||||
#ifdef SPDLOG_PREVENT_CHILD_FD
|
||||
#if defined(SPDLOG_PREVENT_CHILD_FD)
|
||||
if (*fp != nullptr)
|
||||
{
|
||||
prevent_child_fd(*fp);
|
||||
auto file_handle = reinterpret_cast<HANDLE>(_get_osfhandle(::_fileno(*fp)));
|
||||
if (!::SetHandleInformation(file_handle, HANDLE_FLAG_INHERIT, 0))
|
||||
{
|
||||
::fclose(*fp);
|
||||
*fp = nullptr;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#else // unix
|
||||
#if defined(SPDLOG_PREVENT_CHILD_FD)
|
||||
const int mode_flag = mode == SPDLOG_FILENAME_T("ab") ? O_APPEND : O_TRUNC;
|
||||
const int fd = ::open((filename.c_str()), O_CREAT | O_WRONLY | O_CLOEXEC | mode_flag, mode_t(0644));
|
||||
if (fd == -1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
*fp = ::fdopen(fd, mode.c_str());
|
||||
if (*fp == nullptr)
|
||||
{
|
||||
::close(fd);
|
||||
}
|
||||
#else
|
||||
*fp = ::fopen((filename.c_str()), mode.c_str());
|
||||
#endif
|
||||
#endif
|
||||
|
||||
return *fp == nullptr;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE int remove(const filename_t &filename) SPDLOG_NOEXCEPT
|
||||
{
|
||||
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
|
||||
return _wremove(filename.c_str());
|
||||
return ::_wremove(filename.c_str());
|
||||
#else
|
||||
return std::remove(filename.c_str());
|
||||
#endif
|
||||
@@ -175,28 +171,28 @@ SPDLOG_INLINE int remove(const filename_t &filename) SPDLOG_NOEXCEPT
|
||||
|
||||
SPDLOG_INLINE int remove_if_exists(const filename_t &filename) SPDLOG_NOEXCEPT
|
||||
{
|
||||
return file_exists(filename) ? remove(filename) : 0;
|
||||
return path_exists(filename) ? remove(filename) : 0;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT
|
||||
{
|
||||
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
|
||||
return _wrename(filename1.c_str(), filename2.c_str());
|
||||
return ::_wrename(filename1.c_str(), filename2.c_str());
|
||||
#else
|
||||
return std::rename(filename1.c_str(), filename2.c_str());
|
||||
#endif
|
||||
}
|
||||
|
||||
// Return true if file exists
|
||||
SPDLOG_INLINE bool file_exists(const filename_t &filename) SPDLOG_NOEXCEPT
|
||||
// Return true if path exists (file or directory)
|
||||
SPDLOG_INLINE bool path_exists(const filename_t &filename) SPDLOG_NOEXCEPT
|
||||
{
|
||||
#ifdef _WIN32
|
||||
#ifdef SPDLOG_WCHAR_FILENAMES
|
||||
auto attribs = GetFileAttributesW(filename.c_str());
|
||||
auto attribs = ::GetFileAttributesW(filename.c_str());
|
||||
#else
|
||||
auto attribs = GetFileAttributesA(filename.c_str());
|
||||
auto attribs = ::GetFileAttributesA(filename.c_str());
|
||||
#endif
|
||||
return (attribs != INVALID_FILE_ATTRIBUTES && !(attribs & FILE_ATTRIBUTE_DIRECTORY));
|
||||
return attribs != INVALID_FILE_ATTRIBUTES;
|
||||
#else // common linux/unix all have the stat system call
|
||||
struct stat buffer;
|
||||
return (::stat(filename.c_str(), &buffer) == 0);
|
||||
@@ -208,19 +204,19 @@ SPDLOG_INLINE size_t filesize(FILE *f)
|
||||
{
|
||||
if (f == nullptr)
|
||||
{
|
||||
SPDLOG_THROW(spdlog_ex("Failed getting file size. fd is null"));
|
||||
throw_spdlog_ex("Failed getting file size. fd is null");
|
||||
}
|
||||
#if defined(_WIN32) && !defined(__CYGWIN__)
|
||||
int fd = _fileno(f);
|
||||
int fd = ::_fileno(f);
|
||||
#if _WIN64 // 64 bits
|
||||
__int64 ret = _filelengthi64(fd);
|
||||
__int64 ret = ::_filelengthi64(fd);
|
||||
if (ret >= 0)
|
||||
{
|
||||
return static_cast<size_t>(ret);
|
||||
}
|
||||
|
||||
#else // windows 32 bits
|
||||
long ret = _filelength(fd);
|
||||
long ret = ::_filelength(fd);
|
||||
if (ret >= 0)
|
||||
{
|
||||
return static_cast<size_t>(ret);
|
||||
@@ -228,7 +224,12 @@ SPDLOG_INLINE size_t filesize(FILE *f)
|
||||
#endif
|
||||
|
||||
#else // unix
|
||||
// OpenBSD doesn't compile with :: before the fileno(..)
|
||||
#if defined(__OpenBSD__)
|
||||
int fd = fileno(f);
|
||||
#else
|
||||
int fd = ::fileno(f);
|
||||
#endif
|
||||
// 64 bits(but not in osx or cygwin, where fstat64 is deprecated)
|
||||
#if (defined(__linux__) || defined(__sun) || defined(_AIX)) && (defined(__LP64__) || defined(_LP64))
|
||||
struct stat64 st;
|
||||
@@ -236,16 +237,16 @@ SPDLOG_INLINE size_t filesize(FILE *f)
|
||||
{
|
||||
return static_cast<size_t>(st.st_size);
|
||||
}
|
||||
#else // unix 32 bits or cygwin
|
||||
#else // other unix or linux 32 bits or cygwin
|
||||
struct stat st;
|
||||
|
||||
if (::fstat(fd, &st) == 0)
|
||||
{
|
||||
return static_cast<size_t>(st.st_size);
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
SPDLOG_THROW(spdlog_ex("Failed getting file size from fd", errno));
|
||||
throw_spdlog_ex("Failed getting file size from fd", errno);
|
||||
return 0; // will not be reached.
|
||||
}
|
||||
|
||||
// Return utc offset in minutes or throw spdlog_ex on failure
|
||||
@@ -255,13 +256,13 @@ SPDLOG_INLINE int utc_minutes_offset(const std::tm &tm)
|
||||
#ifdef _WIN32
|
||||
#if _WIN32_WINNT < _WIN32_WINNT_WS08
|
||||
TIME_ZONE_INFORMATION tzinfo;
|
||||
auto rv = GetTimeZoneInformation(&tzinfo);
|
||||
auto rv = ::GetTimeZoneInformation(&tzinfo);
|
||||
#else
|
||||
DYNAMIC_TIME_ZONE_INFORMATION tzinfo;
|
||||
auto rv = GetDynamicTimeZoneInformation(&tzinfo);
|
||||
auto rv = ::GetDynamicTimeZoneInformation(&tzinfo);
|
||||
#endif
|
||||
if (rv == TIME_ZONE_ID_INVALID)
|
||||
SPDLOG_THROW(spdlog::spdlog_ex("Failed getting timezone info. ", errno));
|
||||
throw_spdlog_ex("Failed getting timezone info. ", errno);
|
||||
|
||||
int offset = -tzinfo.Bias;
|
||||
if (tm.tm_isdst)
|
||||
@@ -275,7 +276,7 @@ SPDLOG_INLINE int utc_minutes_offset(const std::tm &tm)
|
||||
return offset;
|
||||
#else
|
||||
|
||||
#if defined(sun) || defined(__sun) || defined(_AIX)
|
||||
#if defined(sun) || defined(__sun) || defined(_AIX) || (!defined(_BSD_SOURCE) && !defined(_GNU_SOURCE))
|
||||
// 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris
|
||||
struct helper
|
||||
{
|
||||
@@ -324,15 +325,15 @@ SPDLOG_INLINE size_t _thread_id() SPDLOG_NOEXCEPT
|
||||
#if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
|
||||
#define SYS_gettid __NR_gettid
|
||||
#endif
|
||||
return static_cast<size_t>(syscall(SYS_gettid));
|
||||
return static_cast<size_t>(::syscall(SYS_gettid));
|
||||
#elif defined(_AIX) || defined(__DragonFly__) || defined(__FreeBSD__)
|
||||
return static_cast<size_t>(pthread_getthreadid_np());
|
||||
return static_cast<size_t>(::pthread_getthreadid_np());
|
||||
#elif defined(__NetBSD__)
|
||||
return static_cast<size_t>(_lwp_self());
|
||||
return static_cast<size_t>(::_lwp_self());
|
||||
#elif defined(__OpenBSD__)
|
||||
return static_cast<size_t>(getthrid());
|
||||
return static_cast<size_t>(::getthrid());
|
||||
#elif defined(__sun)
|
||||
return static_cast<size_t>(thr_self());
|
||||
return static_cast<size_t>(::thr_self());
|
||||
#elif __APPLE__
|
||||
uint64_t tid;
|
||||
pthread_threadid_np(nullptr, &tid);
|
||||
@@ -390,13 +391,13 @@ SPDLOG_INLINE int pid() SPDLOG_NOEXCEPT
|
||||
}
|
||||
|
||||
// Determine if the terminal supports colors
|
||||
// Source: https://github.com/agauniyal/rang/
|
||||
// Based on: https://github.com/agauniyal/rang/
|
||||
SPDLOG_INLINE bool is_color_terminal() SPDLOG_NOEXCEPT
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return true;
|
||||
#else
|
||||
static constexpr std::array<const char *, 14> Terms = {
|
||||
static constexpr std::array<const char *, 14> terms = {
|
||||
{"ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm"}};
|
||||
|
||||
const char *env_p = std::getenv("TERM");
|
||||
@@ -406,29 +407,29 @@ SPDLOG_INLINE bool is_color_terminal() SPDLOG_NOEXCEPT
|
||||
}
|
||||
|
||||
static const bool result =
|
||||
std::any_of(std::begin(Terms), std::end(Terms), [&](const char *term) { return std::strstr(env_p, term) != nullptr; });
|
||||
std::any_of(terms.begin(), terms.end(), [&](const char *term) { return std::strstr(env_p, term) != nullptr; });
|
||||
return result;
|
||||
#endif
|
||||
}
|
||||
|
||||
// Detrmine if the terminal attached
|
||||
// Determine if the terminal attached
|
||||
// Source: https://github.com/agauniyal/rang/
|
||||
SPDLOG_INLINE bool in_terminal(FILE *file) SPDLOG_NOEXCEPT
|
||||
{
|
||||
|
||||
#ifdef _WIN32
|
||||
return _isatty(_fileno(file)) != 0;
|
||||
return ::_isatty(_fileno(file)) != 0;
|
||||
#else
|
||||
return isatty(fileno(file)) != 0;
|
||||
return ::isatty(fileno(file)) != 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if (defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)) && defined(_WIN32)
|
||||
SPDLOG_INLINE void wstr_to_utf8buf(wstring_view_t wstr, memory_buf_t &target)
|
||||
{
|
||||
if (wstr.size() > static_cast<size_t>(std::numeric_limits<int>::max()))
|
||||
if (wstr.size() > static_cast<size_t>((std::numeric_limits<int>::max)()))
|
||||
{
|
||||
SPDLOG_THROW(spdlog::spdlog_ex("UTF-16 string is too big to be converted to UTF-8"));
|
||||
throw_spdlog_ex("UTF-16 string is too big to be converted to UTF-8");
|
||||
}
|
||||
|
||||
int wstr_size = static_cast<int>(wstr.size());
|
||||
@@ -456,10 +457,98 @@ SPDLOG_INLINE void wstr_to_utf8buf(wstring_view_t wstr, memory_buf_t &target)
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_THROW(spdlog::spdlog_ex(fmt::format("WideCharToMultiByte failed. Last error: {}", ::GetLastError())));
|
||||
throw_spdlog_ex(fmt::format("WideCharToMultiByte failed. Last error: {}", ::GetLastError()));
|
||||
}
|
||||
#endif // (defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)) && defined(_WIN32)
|
||||
|
||||
// return true on success
|
||||
static SPDLOG_INLINE bool mkdir_(const filename_t &path)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
#ifdef SPDLOG_WCHAR_FILENAMES
|
||||
return ::_wmkdir(path.c_str()) == 0;
|
||||
#else
|
||||
return ::_mkdir(path.c_str()) == 0;
|
||||
#endif
|
||||
#else
|
||||
return ::mkdir(path.c_str(), mode_t(0755)) == 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
// create the given directory - and all directories leading to it
|
||||
// return true on success or if the directory already exists
|
||||
SPDLOG_INLINE bool create_dir(filename_t path)
|
||||
{
|
||||
if (path_exists(path))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (path.empty())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
// support forward slash in windows
|
||||
std::replace(path.begin(), path.end(), '/', folder_sep);
|
||||
#endif
|
||||
|
||||
size_t search_offset = 0;
|
||||
do
|
||||
{
|
||||
auto token_pos = path.find(folder_sep, search_offset);
|
||||
// treat the entire path as a folder if no folder separator not found
|
||||
if (token_pos == filename_t::npos)
|
||||
{
|
||||
token_pos = path.size();
|
||||
}
|
||||
|
||||
auto subdir = path.substr(0, token_pos);
|
||||
|
||||
if (!subdir.empty() && !path_exists(subdir) && !mkdir_(subdir))
|
||||
{
|
||||
return false; // return error if failed creating dir
|
||||
}
|
||||
search_offset = token_pos + 1;
|
||||
} while (search_offset < path.size());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Return directory name from given path or empty string
|
||||
// "abc/file" => "abc"
|
||||
// "abc/" => "abc"
|
||||
// "abc" => ""
|
||||
// "abc///" => "abc//"
|
||||
SPDLOG_INLINE filename_t dir_name(filename_t path)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
// support forward slash in windows
|
||||
std::replace(path.begin(), path.end(), '/', folder_sep);
|
||||
#endif
|
||||
auto pos = path.find_last_of(folder_sep);
|
||||
return pos != filename_t::npos ? path.substr(0, pos) : filename_t{};
|
||||
}
|
||||
|
||||
std::string SPDLOG_INLINE getenv(const char *field)
|
||||
{
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#if defined(__cplusplus_winrt)
|
||||
return std::string{}; // not supported under uwp
|
||||
#else
|
||||
size_t len = 0;
|
||||
char buf[128];
|
||||
bool ok = ::getenv_s(&len, buf, sizeof(buf), field) == 0;
|
||||
return ok ? buf : std::string{};
|
||||
#endif
|
||||
#else // revert to getenv
|
||||
char *buf = ::getenv(field);
|
||||
return buf ? buf : std::string{};
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace os
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
||||
|
@@ -3,22 +3,22 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/common.h"
|
||||
#include <spdlog/common.h>
|
||||
#include <ctime> // std::time_t
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
namespace os {
|
||||
|
||||
spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT;
|
||||
|
||||
std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT;
|
||||
|
||||
std::tm localtime() SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API std::tm localtime() SPDLOG_NOEXCEPT;
|
||||
|
||||
std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT;
|
||||
|
||||
std::tm gmtime() SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API std::tm gmtime() SPDLOG_NOEXCEPT;
|
||||
|
||||
// eol definition
|
||||
#if !defined(SPDLOG_EOL)
|
||||
@@ -33,62 +33,75 @@ SPDLOG_CONSTEXPR static const char *default_eol = SPDLOG_EOL;
|
||||
|
||||
// folder separator
|
||||
#ifdef _WIN32
|
||||
const char folder_sep = '\\';
|
||||
static const char folder_sep = '\\';
|
||||
#else
|
||||
SPDLOG_CONSTEXPR static const char folder_sep = '/';
|
||||
#endif
|
||||
|
||||
void prevent_child_fd(FILE *f);
|
||||
|
||||
// fopen_s on non windows for writing
|
||||
bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode);
|
||||
SPDLOG_API bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode);
|
||||
|
||||
// Remove filename. return 0 on success
|
||||
int remove(const filename_t &filename) SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API int remove(const filename_t &filename) SPDLOG_NOEXCEPT;
|
||||
|
||||
// Remove file if exists. return 0 on success
|
||||
// Note: Non atomic (might return failure to delete if concurrently deleted by other process/thread)
|
||||
int remove_if_exists(const filename_t &filename) SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API int remove_if_exists(const filename_t &filename) SPDLOG_NOEXCEPT;
|
||||
|
||||
int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT;
|
||||
|
||||
// Return if file exists.
|
||||
bool file_exists(const filename_t &filename) SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API bool path_exists(const filename_t &filename) SPDLOG_NOEXCEPT;
|
||||
|
||||
// Return file size according to open FILE* object
|
||||
size_t filesize(FILE *f);
|
||||
SPDLOG_API size_t filesize(FILE *f);
|
||||
|
||||
// Return utc offset in minutes or throw spdlog_ex on failure
|
||||
int utc_minutes_offset(const std::tm &tm = details::os::localtime());
|
||||
SPDLOG_API int utc_minutes_offset(const std::tm &tm = details::os::localtime());
|
||||
|
||||
// Return current thread id as size_t
|
||||
// It exists because the std::this_thread::get_id() is much slower(especially
|
||||
// under VS 2013)
|
||||
size_t _thread_id() SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API size_t _thread_id() SPDLOG_NOEXCEPT;
|
||||
|
||||
// Return current thread id as size_t (from thread local storage)
|
||||
size_t thread_id() SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API size_t thread_id() SPDLOG_NOEXCEPT;
|
||||
|
||||
// This is avoid msvc issue in sleep_for that happens if the clock changes.
|
||||
// See https://github.com/gabime/spdlog/issues/609
|
||||
void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT;
|
||||
|
||||
std::string filename_to_str(const filename_t &filename);
|
||||
SPDLOG_API std::string filename_to_str(const filename_t &filename);
|
||||
|
||||
int pid() SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API int pid() SPDLOG_NOEXCEPT;
|
||||
|
||||
// Determine if the terminal supports colors
|
||||
// Source: https://github.com/agauniyal/rang/
|
||||
bool is_color_terminal() SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API bool is_color_terminal() SPDLOG_NOEXCEPT;
|
||||
|
||||
// Detrmine if the terminal attached
|
||||
// Determine if the terminal attached
|
||||
// Source: https://github.com/agauniyal/rang/
|
||||
bool in_terminal(FILE *file) SPDLOG_NOEXCEPT;
|
||||
SPDLOG_API bool in_terminal(FILE *file) SPDLOG_NOEXCEPT;
|
||||
|
||||
#if (defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)) && defined(_WIN32)
|
||||
void wstr_to_utf8buf(wstring_view_t wstr, memory_buf_t &target);
|
||||
SPDLOG_API void wstr_to_utf8buf(wstring_view_t wstr, memory_buf_t &target);
|
||||
#endif
|
||||
|
||||
// Return directory name from given path or empty string
|
||||
// "abc/file" => "abc"
|
||||
// "abc/" => "abc"
|
||||
// "abc" => ""
|
||||
// "abc///" => "abc//"
|
||||
SPDLOG_API filename_t dir_name(filename_t path);
|
||||
|
||||
// Create a dir from the given path.
|
||||
// Return true if succeeded or if this dir already exists.
|
||||
SPDLOG_API bool create_dir(filename_t path);
|
||||
|
||||
// non thread safe, cross platform getenv/getenv_s
|
||||
// return empty string if field not found
|
||||
SPDLOG_API std::string getenv(const char *field);
|
||||
|
||||
} // namespace os
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
||||
|
@@ -4,7 +4,7 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/details/periodic_worker.h"
|
||||
#include <spdlog/details/periodic_worker.h>
|
||||
#endif
|
||||
|
||||
namespace spdlog {
|
||||
|
@@ -17,7 +17,7 @@
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
|
||||
class periodic_worker
|
||||
class SPDLOG_API periodic_worker
|
||||
{
|
||||
public:
|
||||
periodic_worker(const std::function<void()> &callback_fun, std::chrono::seconds interval);
|
||||
|
@@ -4,20 +4,20 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/details/registry.h"
|
||||
#include <spdlog/details/registry.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/common.h"
|
||||
#include "spdlog/details/periodic_worker.h"
|
||||
#include "spdlog/logger.h"
|
||||
#include "spdlog/details/pattern_formatter.h"
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/periodic_worker.h>
|
||||
#include <spdlog/logger.h>
|
||||
#include <spdlog/pattern_formatter.h>
|
||||
|
||||
#ifndef SPDLOG_DISABLE_DEFAULT_LOGGER
|
||||
// support for the default stdout color logger
|
||||
#ifdef _WIN32
|
||||
#include "spdlog/sinks/wincolor_sink.h"
|
||||
#include <spdlog/sinks/wincolor_sink.h>
|
||||
#else
|
||||
#include "spdlog/sinks/ansicolor_sink.h"
|
||||
#include <spdlog/sinks/ansicolor_sink.h>
|
||||
#endif
|
||||
#endif // SPDLOG_DISABLE_DEFAULT_LOGGER
|
||||
|
||||
@@ -48,6 +48,9 @@ SPDLOG_INLINE registry::registry()
|
||||
|
||||
#endif // SPDLOG_DISABLE_DEFAULT_LOGGER
|
||||
}
|
||||
|
||||
SPDLOG_INLINE registry::~registry() = default;
|
||||
|
||||
SPDLOG_INLINE void registry::register_logger(std::shared_ptr<logger> new_logger)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
@@ -64,7 +67,7 @@ SPDLOG_INLINE void registry::initialize_logger(std::shared_ptr<logger> new_logge
|
||||
new_logger->set_error_handler(err_handler_);
|
||||
}
|
||||
|
||||
new_logger->set_level(level_);
|
||||
new_logger->set_level(levels_.get(new_logger->name()));
|
||||
new_logger->flush_on(flush_level_);
|
||||
|
||||
if (backtrace_n_messages_ > 0)
|
||||
@@ -168,7 +171,7 @@ SPDLOG_INLINE void registry::set_level(level::level_enum log_level)
|
||||
{
|
||||
l.second->set_level(log_level);
|
||||
}
|
||||
level_ = log_level;
|
||||
levels_.set_default(log_level);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::flush_on(level::level_enum log_level)
|
||||
@@ -184,7 +187,7 @@ SPDLOG_INLINE void registry::flush_on(level::level_enum log_level)
|
||||
SPDLOG_INLINE void registry::flush_every(std::chrono::seconds interval)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(flusher_mutex_);
|
||||
std::function<void()> clbk = std::bind(®istry::flush_all, this);
|
||||
auto clbk = [this]() { this->flush_all(); };
|
||||
periodic_flusher_ = details::make_unique<periodic_worker>(clbk, interval);
|
||||
}
|
||||
|
||||
@@ -254,10 +257,21 @@ SPDLOG_INLINE std::recursive_mutex ®istry::tp_mutex()
|
||||
return tp_mutex_;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::set_automatic_registration(bool automatic_regsistration)
|
||||
SPDLOG_INLINE void registry::set_automatic_registration(bool automatic_registration)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
automatic_registration_ = automatic_regsistration;
|
||||
automatic_registration_ = automatic_registration;
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void registry::update_levels(cfg::log_levels levels)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(logger_map_mutex_);
|
||||
levels_ = std::move(levels);
|
||||
for (auto &l : loggers_)
|
||||
{
|
||||
auto &logger = l.second;
|
||||
logger->set_level(levels_.get(logger->name()));
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE registry ®istry::instance()
|
||||
@@ -270,7 +284,7 @@ SPDLOG_INLINE void registry::throw_if_exists_(const std::string &logger_name)
|
||||
{
|
||||
if (loggers_.find(logger_name) != loggers_.end())
|
||||
{
|
||||
SPDLOG_THROW(spdlog_ex("logger with name '" + logger_name + "' already exists"));
|
||||
throw_spdlog_ex("logger with name '" + logger_name + "' already exists");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,5 +294,6 @@ SPDLOG_INLINE void registry::register_logger_(std::shared_ptr<logger> new_logger
|
||||
throw_if_exists_(logger_name);
|
||||
loggers_[logger_name] = std::move(new_logger);
|
||||
}
|
||||
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
||||
|
@@ -8,7 +8,8 @@
|
||||
// If user requests a non existing logger, nullptr will be returned
|
||||
// This class is thread safe
|
||||
|
||||
#include "spdlog/common.h"
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/cfg/log_levels.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
@@ -24,7 +25,7 @@ namespace details {
|
||||
class thread_pool;
|
||||
class periodic_worker;
|
||||
|
||||
class registry
|
||||
class SPDLOG_API registry
|
||||
{
|
||||
public:
|
||||
registry(const registry &) = delete;
|
||||
@@ -77,21 +78,23 @@ public:
|
||||
|
||||
std::recursive_mutex &tp_mutex();
|
||||
|
||||
void set_automatic_registration(bool automatic_regsistration);
|
||||
void set_automatic_registration(bool automatic_registration);
|
||||
|
||||
void update_levels(cfg::log_levels levels);
|
||||
|
||||
static registry &instance();
|
||||
|
||||
private:
|
||||
registry();
|
||||
~registry() = default;
|
||||
~registry();
|
||||
|
||||
void throw_if_exists_(const std::string &logger_name);
|
||||
void register_logger_(std::shared_ptr<logger> new_logger);
|
||||
std::mutex logger_map_mutex_, flusher_mutex_;
|
||||
std::recursive_mutex tp_mutex_;
|
||||
std::unordered_map<std::string, std::shared_ptr<logger>> loggers_;
|
||||
cfg::log_levels levels_;
|
||||
std::unique_ptr<formatter> formatter_;
|
||||
level::level_enum level_ = level::info;
|
||||
level::level_enum flush_level_ = level::off;
|
||||
void (*err_handler_)(const std::string &msg);
|
||||
std::shared_ptr<thread_pool> tp_;
|
||||
|
175
include/spdlog/details/tcp_client-windows.h
Normal file
175
include/spdlog/details/tcp_client-windows.h
Normal file
@@ -0,0 +1,175 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
// tcp client helper
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/os.h>
|
||||
|
||||
#include <windows.h>
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <string>
|
||||
|
||||
#pragma comment(lib, "Ws2_32.lib")
|
||||
#pragma comment(lib, "Mswsock.lib")
|
||||
#pragma comment(lib, "AdvApi32.lib")
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
class tcp_client
|
||||
{
|
||||
SOCKET socket_ = INVALID_SOCKET;
|
||||
|
||||
static bool winsock_initialized_()
|
||||
{
|
||||
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
if (s == INVALID_SOCKET)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
closesocket(s);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
static void init_winsock_()
|
||||
{
|
||||
WSADATA wsaData;
|
||||
auto rv = WSAStartup(MAKEWORD(2, 2), &wsaData);
|
||||
if (rv != 0)
|
||||
{
|
||||
throw_winsock_error_("WSAStartup failed", ::WSAGetLastError());
|
||||
}
|
||||
}
|
||||
|
||||
static void throw_winsock_error_(const std::string &msg, int last_error)
|
||||
{
|
||||
char buf[512];
|
||||
::FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, last_error,
|
||||
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, (sizeof(buf) / sizeof(char)), NULL);
|
||||
|
||||
throw_spdlog_ex(fmt::format("tcp_sink - {}: {}", msg, buf));
|
||||
}
|
||||
|
||||
public:
|
||||
bool is_connected() const
|
||||
{
|
||||
return socket_ != INVALID_SOCKET;
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
::closesocket(socket_);
|
||||
socket_ = INVALID_SOCKET;
|
||||
WSACleanup();
|
||||
}
|
||||
|
||||
SOCKET fd() const
|
||||
{
|
||||
return socket_;
|
||||
}
|
||||
|
||||
~tcp_client()
|
||||
{
|
||||
close();
|
||||
}
|
||||
|
||||
// try to connect or throw on failure
|
||||
void connect(const std::string &host, int port)
|
||||
{
|
||||
// initialize winsock if needed
|
||||
if (!winsock_initialized_())
|
||||
{
|
||||
init_winsock_();
|
||||
}
|
||||
|
||||
if (is_connected())
|
||||
{
|
||||
close();
|
||||
}
|
||||
struct addrinfo hints
|
||||
{};
|
||||
ZeroMemory(&hints, sizeof(hints));
|
||||
|
||||
hints.ai_family = AF_INET; // IPv4
|
||||
hints.ai_socktype = SOCK_STREAM; // TCP
|
||||
hints.ai_flags = AI_NUMERICSERV; // port passed as as numeric value
|
||||
hints.ai_protocol = 0;
|
||||
|
||||
auto port_str = std::to_string(port);
|
||||
struct addrinfo *addrinfo_result;
|
||||
auto rv = ::getaddrinfo(host.c_str(), port_str.c_str(), &hints, &addrinfo_result);
|
||||
int last_error = 0;
|
||||
if (rv != 0)
|
||||
{
|
||||
last_error = ::WSAGetLastError();
|
||||
WSACleanup();
|
||||
throw_winsock_error_("getaddrinfo failed", last_error);
|
||||
}
|
||||
|
||||
// Try each address until we successfully connect(2).
|
||||
|
||||
for (auto *rp = addrinfo_result; rp != nullptr; rp = rp->ai_next)
|
||||
{
|
||||
socket_ = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
|
||||
if (socket_ == INVALID_SOCKET)
|
||||
{
|
||||
last_error = ::WSAGetLastError();
|
||||
WSACleanup();
|
||||
continue;
|
||||
}
|
||||
if (::connect(socket_, rp->ai_addr, (int)rp->ai_addrlen) == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
last_error = ::WSAGetLastError();
|
||||
close();
|
||||
}
|
||||
}
|
||||
::freeaddrinfo(addrinfo_result);
|
||||
if (socket_ == INVALID_SOCKET)
|
||||
{
|
||||
WSACleanup();
|
||||
throw_winsock_error_("connect failed", last_error);
|
||||
}
|
||||
|
||||
// set TCP_NODELAY
|
||||
int enable_flag = 1;
|
||||
::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, (char *)&enable_flag, sizeof(enable_flag));
|
||||
}
|
||||
|
||||
// Send exactly n_bytes of the given data.
|
||||
// On error close the connection and throw.
|
||||
void send(const char *data, size_t n_bytes)
|
||||
{
|
||||
size_t bytes_sent = 0;
|
||||
while (bytes_sent < n_bytes)
|
||||
{
|
||||
const int send_flags = 0;
|
||||
auto write_result = ::send(socket_, data + bytes_sent, (int)(n_bytes - bytes_sent), send_flags);
|
||||
if (write_result == SOCKET_ERROR)
|
||||
{
|
||||
int last_error = ::WSAGetLastError();
|
||||
close();
|
||||
throw_winsock_error_("send failed", last_error);
|
||||
}
|
||||
|
||||
if (write_result == 0) // (probably should not happen but in any case..)
|
||||
{
|
||||
break;
|
||||
}
|
||||
bytes_sent += static_cast<size_t>(write_result);
|
||||
}
|
||||
}
|
||||
};
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
145
include/spdlog/details/tcp_client.h
Normal file
145
include/spdlog/details/tcp_client.h
Normal file
@@ -0,0 +1,145 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifdef _WIN32
|
||||
#error include tcp_client-windows.h instead
|
||||
#endif
|
||||
|
||||
// tcp client helper
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/os.h>
|
||||
|
||||
#include <sys/socket.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <unistd.h>
|
||||
#include <netdb.h>
|
||||
#include <netinet/tcp.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
class tcp_client
|
||||
{
|
||||
int socket_ = -1;
|
||||
|
||||
public:
|
||||
bool is_connected() const
|
||||
{
|
||||
return socket_ != -1;
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
if (is_connected())
|
||||
{
|
||||
::close(socket_);
|
||||
socket_ = -1;
|
||||
}
|
||||
}
|
||||
|
||||
int fd() const
|
||||
{
|
||||
return socket_;
|
||||
}
|
||||
|
||||
~tcp_client()
|
||||
{
|
||||
close();
|
||||
}
|
||||
|
||||
// try to connect or throw on failure
|
||||
void connect(const std::string &host, int port)
|
||||
{
|
||||
close();
|
||||
struct addrinfo hints
|
||||
{};
|
||||
memset(&hints, 0, sizeof(struct addrinfo));
|
||||
hints.ai_family = AF_INET; // IPv4
|
||||
hints.ai_socktype = SOCK_STREAM; // TCP
|
||||
hints.ai_flags = AI_NUMERICSERV; // port passed as as numeric value
|
||||
hints.ai_protocol = 0;
|
||||
|
||||
auto port_str = std::to_string(port);
|
||||
struct addrinfo *addrinfo_result;
|
||||
auto rv = ::getaddrinfo(host.c_str(), port_str.c_str(), &hints, &addrinfo_result);
|
||||
if (rv != 0)
|
||||
{
|
||||
auto msg = fmt::format("::getaddrinfo failed: {}", gai_strerror(rv));
|
||||
throw_spdlog_ex(msg);
|
||||
}
|
||||
|
||||
// Try each address until we successfully connect(2).
|
||||
int last_errno = 0;
|
||||
for (auto *rp = addrinfo_result; rp != nullptr; rp = rp->ai_next)
|
||||
{
|
||||
int const flags = SOCK_CLOEXEC;
|
||||
socket_ = ::socket(rp->ai_family, rp->ai_socktype | flags, rp->ai_protocol);
|
||||
if (socket_ == -1)
|
||||
{
|
||||
last_errno = errno;
|
||||
continue;
|
||||
}
|
||||
rv = ::connect(socket_, rp->ai_addr, rp->ai_addrlen);
|
||||
if (rv == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
last_errno = errno;
|
||||
::close(socket_);
|
||||
socket_ = -1;
|
||||
}
|
||||
}
|
||||
::freeaddrinfo(addrinfo_result);
|
||||
if (socket_ == -1)
|
||||
{
|
||||
throw_spdlog_ex("::connect failed", last_errno);
|
||||
}
|
||||
|
||||
// set TCP_NODELAY
|
||||
int enable_flag = 1;
|
||||
::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, (char *)&enable_flag, sizeof(enable_flag));
|
||||
|
||||
// prevent sigpipe on systems where MSG_NOSIGNAL is not available
|
||||
#if defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL)
|
||||
::setsockopt(socket_, SOL_SOCKET, SO_NOSIGPIPE, (char *)&enable_flag, sizeof(enable_flag));
|
||||
#endif
|
||||
|
||||
#if !defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL)
|
||||
#error "tcp_sink would raise SIGPIPE since niether SO_NOSIGPIPE nor MSG_NOSIGNAL are available"
|
||||
#endif
|
||||
}
|
||||
|
||||
// Send exactly n_bytes of the given data.
|
||||
// On error close the connection and throw.
|
||||
void send(const char *data, size_t n_bytes)
|
||||
{
|
||||
size_t bytes_sent = 0;
|
||||
while (bytes_sent < n_bytes)
|
||||
{
|
||||
#if defined(MSG_NOSIGNAL)
|
||||
const int send_flags = MSG_NOSIGNAL;
|
||||
#else
|
||||
const int send_flags = 0;
|
||||
#endif
|
||||
auto write_result = ::send(socket_, data + bytes_sent, n_bytes - bytes_sent, send_flags);
|
||||
if (write_result < 0)
|
||||
{
|
||||
close();
|
||||
throw_spdlog_ex("write(2) failed", errno);
|
||||
}
|
||||
|
||||
if (write_result == 0) // (probably should not happen but in any case..)
|
||||
{
|
||||
break;
|
||||
}
|
||||
bytes_sent += static_cast<size_t>(write_result);
|
||||
}
|
||||
}
|
||||
};
|
||||
} // namespace details
|
||||
} // namespace spdlog
|
@@ -4,10 +4,11 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/details/thread_pool.h"
|
||||
#include <spdlog/details/thread_pool.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/common.h"
|
||||
#include <spdlog/common.h>
|
||||
#include <cassert>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
@@ -17,8 +18,8 @@ SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items, size_t threads_n, std
|
||||
{
|
||||
if (threads_n == 0 || threads_n > 1000)
|
||||
{
|
||||
SPDLOG_THROW(spdlog_ex("spdlog::thread_pool(): invalid threads_n param (valid "
|
||||
"range is 1-1000)"));
|
||||
throw_spdlog_ex("spdlog::thread_pool(): invalid threads_n param (valid "
|
||||
"range is 1-1000)");
|
||||
}
|
||||
for (size_t i = 0; i < threads_n; i++)
|
||||
{
|
||||
@@ -81,7 +82,7 @@ void SPDLOG_INLINE thread_pool::post_async_msg_(async_msg &&new_msg, async_overf
|
||||
|
||||
void SPDLOG_INLINE thread_pool::worker_loop_()
|
||||
{
|
||||
while (process_next_msg_()) {};
|
||||
while (process_next_msg_()) {}
|
||||
}
|
||||
|
||||
// process next message in the queue
|
||||
@@ -98,25 +99,21 @@ bool SPDLOG_INLINE thread_pool::process_next_msg_()
|
||||
|
||||
switch (incoming_async_msg.msg_type)
|
||||
{
|
||||
case async_msg_type::log:
|
||||
{
|
||||
case async_msg_type::log: {
|
||||
incoming_async_msg.worker_ptr->backend_sink_it_(incoming_async_msg);
|
||||
return true;
|
||||
}
|
||||
case async_msg_type::flush:
|
||||
{
|
||||
case async_msg_type::flush: {
|
||||
incoming_async_msg.worker_ptr->backend_flush_();
|
||||
return true;
|
||||
}
|
||||
|
||||
case async_msg_type::terminate:
|
||||
{
|
||||
case async_msg_type::terminate: {
|
||||
return false;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
assert(false && "Unexpected async_msg_type");
|
||||
default: {
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -3,9 +3,9 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/details/log_msg_buffer.h"
|
||||
#include "spdlog/details/mpmc_blocking_q.h"
|
||||
#include "spdlog/details/os.h"
|
||||
#include <spdlog/details/log_msg_buffer.h>
|
||||
#include <spdlog/details/mpmc_blocking_q.h>
|
||||
#include <spdlog/details/os.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
@@ -27,7 +27,7 @@ enum class async_msg_type
|
||||
terminate
|
||||
};
|
||||
|
||||
#include "spdlog/details/log_msg_buffer.h"
|
||||
#include <spdlog/details/log_msg_buffer.h>
|
||||
// Async msg to move to/from the queue
|
||||
// Movable only. should never be copied
|
||||
struct async_msg : log_msg_buffer
|
||||
@@ -79,7 +79,7 @@ struct async_msg : log_msg_buffer
|
||||
{}
|
||||
};
|
||||
|
||||
class thread_pool
|
||||
class SPDLOG_API thread_pool
|
||||
{
|
||||
public:
|
||||
using item_type = async_msg;
|
||||
|
11
include/spdlog/details/windows_include.h
Normal file
11
include/spdlog/details/windows_include.h
Normal file
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX // prevent windows redefining min/max
|
||||
#endif
|
||||
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
|
||||
#include <windows.h>
|
@@ -5,6 +5,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cctype>
|
||||
|
||||
//
|
||||
// Support for logging binary data as hex
|
||||
// format flags:
|
||||
@@ -12,6 +14,7 @@
|
||||
// {:s} - don't separate each byte with space.
|
||||
// {:p} - don't print the position on each line start.
|
||||
// {:n} - don't split the output to lines.
|
||||
// {:a} - show ASCII if :n is not set
|
||||
|
||||
//
|
||||
// Examples:
|
||||
@@ -20,17 +23,19 @@
|
||||
// logger->info("Some buffer {}", spdlog::to_hex(v));
|
||||
// char buf[128];
|
||||
// logger->info("Some buffer {:X}", spdlog::to_hex(std::begin(buf), std::end(buf)));
|
||||
// logger->info("Some buffer {:X}", spdlog::to_hex(std::begin(buf), std::end(buf), 16));
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
|
||||
template<typename It>
|
||||
class bytes_range
|
||||
class dump_info
|
||||
{
|
||||
public:
|
||||
bytes_range(It range_begin, It range_end)
|
||||
dump_info(It range_begin, It range_end, size_t size_per_line)
|
||||
: begin_(range_begin)
|
||||
, end_(range_end)
|
||||
, size_per_line_(size_per_line)
|
||||
{}
|
||||
|
||||
It begin() const
|
||||
@@ -41,26 +46,31 @@ public:
|
||||
{
|
||||
return end_;
|
||||
}
|
||||
size_t size_per_line() const
|
||||
{
|
||||
return size_per_line_;
|
||||
}
|
||||
|
||||
private:
|
||||
It begin_, end_;
|
||||
size_t size_per_line_;
|
||||
};
|
||||
} // namespace details
|
||||
|
||||
// create a bytes_range that wraps the given container
|
||||
// create a dump_info that wraps the given container
|
||||
template<typename Container>
|
||||
inline details::bytes_range<typename Container::const_iterator> to_hex(const Container &container)
|
||||
inline details::dump_info<typename Container::const_iterator> to_hex(const Container &container, size_t size_per_line = 32)
|
||||
{
|
||||
static_assert(sizeof(typename Container::value_type) == 1, "sizeof(Container::value_type) != 1");
|
||||
using Iter = typename Container::const_iterator;
|
||||
return details::bytes_range<Iter>(std::begin(container), std::end(container));
|
||||
return details::dump_info<Iter>(std::begin(container), std::end(container), size_per_line);
|
||||
}
|
||||
|
||||
// create bytes_range from ranges
|
||||
// create dump_info from ranges
|
||||
template<typename It>
|
||||
inline details::bytes_range<It> to_hex(const It range_begin, const It range_end)
|
||||
inline details::dump_info<It> to_hex(const It range_begin, const It range_end, size_t size_per_line = 32)
|
||||
{
|
||||
return details::bytes_range<It>(range_begin, range_end);
|
||||
return details::dump_info<It>(range_begin, range_end, size_per_line);
|
||||
}
|
||||
|
||||
} // namespace spdlog
|
||||
@@ -68,15 +78,14 @@ inline details::bytes_range<It> to_hex(const It range_begin, const It range_end)
|
||||
namespace fmt {
|
||||
|
||||
template<typename T>
|
||||
struct formatter<spdlog::details::bytes_range<T>>
|
||||
struct formatter<spdlog::details::dump_info<T>>
|
||||
{
|
||||
const std::size_t line_size = 100;
|
||||
const char delimiter = ' ';
|
||||
|
||||
bool put_newlines = true;
|
||||
bool put_delimiters = true;
|
||||
bool use_uppercase = false;
|
||||
bool put_positions = true; // position on start of each line
|
||||
bool show_ascii = false;
|
||||
|
||||
// parse the format string flags
|
||||
template<typename ParseContext>
|
||||
@@ -98,6 +107,13 @@ struct formatter<spdlog::details::bytes_range<T>>
|
||||
break;
|
||||
case 'n':
|
||||
put_newlines = false;
|
||||
show_ascii = false;
|
||||
break;
|
||||
case 'a':
|
||||
if (put_newlines)
|
||||
{
|
||||
show_ascii = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -108,53 +124,83 @@ struct formatter<spdlog::details::bytes_range<T>>
|
||||
|
||||
// format the given bytes range as hex
|
||||
template<typename FormatContext, typename Container>
|
||||
auto format(const spdlog::details::bytes_range<Container> &the_range, FormatContext &ctx) -> decltype(ctx.out())
|
||||
auto format(const spdlog::details::dump_info<Container> &the_range, FormatContext &ctx) -> decltype(ctx.out())
|
||||
{
|
||||
SPDLOG_CONSTEXPR const char *hex_upper = "0123456789ABCDEF";
|
||||
SPDLOG_CONSTEXPR const char *hex_lower = "0123456789abcdef";
|
||||
const char *hex_chars = use_uppercase ? hex_upper : hex_lower;
|
||||
|
||||
std::size_t pos = 0;
|
||||
std::size_t column = line_size;
|
||||
#if FMT_VERSION < 60000
|
||||
auto inserter = ctx.begin();
|
||||
#else
|
||||
auto inserter = ctx.out();
|
||||
#endif
|
||||
|
||||
for (auto &item : the_range)
|
||||
int size_per_line = static_cast<int>(the_range.size_per_line());
|
||||
auto start_of_line = the_range.begin();
|
||||
for (auto i = the_range.begin(); i != the_range.end(); i++)
|
||||
{
|
||||
auto ch = static_cast<unsigned char>(item);
|
||||
pos++;
|
||||
auto ch = static_cast<unsigned char>(*i);
|
||||
|
||||
if (put_newlines && column >= line_size)
|
||||
if (put_newlines && (i == the_range.begin() || i - start_of_line >= size_per_line))
|
||||
{
|
||||
column = put_newline(inserter, pos);
|
||||
if (show_ascii && i != the_range.begin())
|
||||
{
|
||||
*inserter++ = delimiter;
|
||||
*inserter++ = delimiter;
|
||||
for (auto j = start_of_line; j < i; j++)
|
||||
{
|
||||
auto pc = static_cast<unsigned char>(*j);
|
||||
*inserter++ = std::isprint(pc) ? static_cast<char>(*j) : '.';
|
||||
}
|
||||
}
|
||||
|
||||
put_newline(inserter, static_cast<size_t>(i - the_range.begin()));
|
||||
|
||||
// put first byte without delimiter in front of it
|
||||
*inserter++ = hex_chars[(ch >> 4) & 0x0f];
|
||||
*inserter++ = hex_chars[ch & 0x0f];
|
||||
column += 2;
|
||||
start_of_line = i;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (put_delimiters)
|
||||
{
|
||||
*inserter++ = delimiter;
|
||||
++column;
|
||||
}
|
||||
|
||||
*inserter++ = hex_chars[(ch >> 4) & 0x0f];
|
||||
*inserter++ = hex_chars[ch & 0x0f];
|
||||
column += 2;
|
||||
}
|
||||
if (show_ascii) // add ascii to last line
|
||||
{
|
||||
if (the_range.end() - the_range.begin() > size_per_line)
|
||||
{
|
||||
auto blank_num = size_per_line - (the_range.end() - start_of_line);
|
||||
while (blank_num-- > 0)
|
||||
{
|
||||
*inserter++ = delimiter;
|
||||
*inserter++ = delimiter;
|
||||
if (put_delimiters)
|
||||
{
|
||||
*inserter++ = delimiter;
|
||||
}
|
||||
}
|
||||
}
|
||||
*inserter++ = delimiter;
|
||||
*inserter++ = delimiter;
|
||||
for (auto j = start_of_line; j != the_range.end(); j++)
|
||||
{
|
||||
auto pc = static_cast<unsigned char>(*j);
|
||||
*inserter++ = std::isprint(pc) ? static_cast<char>(*j) : '.';
|
||||
}
|
||||
}
|
||||
return inserter;
|
||||
}
|
||||
|
||||
// put newline(and position header)
|
||||
// return the next column
|
||||
template<typename It>
|
||||
std::size_t put_newline(It inserter, std::size_t pos)
|
||||
void put_newline(It inserter, std::size_t pos)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
*inserter++ = '\r';
|
||||
@@ -163,12 +209,7 @@ struct formatter<spdlog::details::bytes_range<T>>
|
||||
|
||||
if (put_positions)
|
||||
{
|
||||
fmt::format_to(inserter, "{:<04X}: ", pos - 1);
|
||||
return 7;
|
||||
}
|
||||
else
|
||||
{
|
||||
return 1;
|
||||
fmt::format_to(inserter, "{:<04X}: ", pos);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
@@ -8,24 +8,299 @@
|
||||
#ifndef FMT_CHRONO_H_
|
||||
#define FMT_CHRONO_H_
|
||||
|
||||
#include "format.h"
|
||||
#include "locale.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <locale>
|
||||
#include <sstream>
|
||||
|
||||
// enable safe chrono durations, unless explicitly disabled
|
||||
#include "format.h"
|
||||
#include "locale.h"
|
||||
|
||||
FMT_BEGIN_NAMESPACE
|
||||
|
||||
// Enable safe chrono durations, unless explicitly disabled.
|
||||
#ifndef FMT_SAFE_DURATION_CAST
|
||||
# define FMT_SAFE_DURATION_CAST 1
|
||||
#endif
|
||||
|
||||
#if FMT_SAFE_DURATION_CAST
|
||||
# include "safe-duration-cast.h"
|
||||
#endif
|
||||
|
||||
FMT_BEGIN_NAMESPACE
|
||||
// For conversion between std::chrono::durations without undefined
|
||||
// behaviour or erroneous results.
|
||||
// This is a stripped down version of duration_cast, for inclusion in fmt.
|
||||
// See https://github.com/pauldreik/safe_duration_cast
|
||||
//
|
||||
// Copyright Paul Dreik 2019
|
||||
namespace safe_duration_cast {
|
||||
|
||||
template <typename To, typename From,
|
||||
FMT_ENABLE_IF(!std::is_same<From, To>::value &&
|
||||
std::numeric_limits<From>::is_signed ==
|
||||
std::numeric_limits<To>::is_signed)>
|
||||
FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
|
||||
ec = 0;
|
||||
using F = std::numeric_limits<From>;
|
||||
using T = std::numeric_limits<To>;
|
||||
static_assert(F::is_integer, "From must be integral");
|
||||
static_assert(T::is_integer, "To must be integral");
|
||||
|
||||
// A and B are both signed, or both unsigned.
|
||||
if (F::digits <= T::digits) {
|
||||
// From fits in To without any problem.
|
||||
} else {
|
||||
// From does not always fit in To, resort to a dynamic check.
|
||||
if (from < T::min() || from > T::max()) {
|
||||
// outside range.
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
}
|
||||
return static_cast<To>(from);
|
||||
}
|
||||
|
||||
/**
|
||||
* converts From to To, without loss. If the dynamic value of from
|
||||
* can't be converted to To without loss, ec is set.
|
||||
*/
|
||||
template <typename To, typename From,
|
||||
FMT_ENABLE_IF(!std::is_same<From, To>::value &&
|
||||
std::numeric_limits<From>::is_signed !=
|
||||
std::numeric_limits<To>::is_signed)>
|
||||
FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
|
||||
ec = 0;
|
||||
using F = std::numeric_limits<From>;
|
||||
using T = std::numeric_limits<To>;
|
||||
static_assert(F::is_integer, "From must be integral");
|
||||
static_assert(T::is_integer, "To must be integral");
|
||||
|
||||
if (F::is_signed && !T::is_signed) {
|
||||
// From may be negative, not allowed!
|
||||
if (fmt::internal::is_negative(from)) {
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
|
||||
// From is positive. Can it always fit in To?
|
||||
if (F::digits <= T::digits) {
|
||||
// yes, From always fits in To.
|
||||
} else {
|
||||
// from may not fit in To, we have to do a dynamic check
|
||||
if (from > static_cast<From>(T::max())) {
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!F::is_signed && T::is_signed) {
|
||||
// can from be held in To?
|
||||
if (F::digits < T::digits) {
|
||||
// yes, From always fits in To.
|
||||
} else {
|
||||
// from may not fit in To, we have to do a dynamic check
|
||||
if (from > static_cast<From>(T::max())) {
|
||||
// outside range.
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// reaching here means all is ok for lossless conversion.
|
||||
return static_cast<To>(from);
|
||||
|
||||
} // function
|
||||
|
||||
template <typename To, typename From,
|
||||
FMT_ENABLE_IF(std::is_same<From, To>::value)>
|
||||
FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
|
||||
ec = 0;
|
||||
return from;
|
||||
} // function
|
||||
|
||||
// clang-format off
|
||||
/**
|
||||
* converts From to To if possible, otherwise ec is set.
|
||||
*
|
||||
* input | output
|
||||
* ---------------------------------|---------------
|
||||
* NaN | NaN
|
||||
* Inf | Inf
|
||||
* normal, fits in output | converted (possibly lossy)
|
||||
* normal, does not fit in output | ec is set
|
||||
* subnormal | best effort
|
||||
* -Inf | -Inf
|
||||
*/
|
||||
// clang-format on
|
||||
template <typename To, typename From,
|
||||
FMT_ENABLE_IF(!std::is_same<From, To>::value)>
|
||||
FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) {
|
||||
ec = 0;
|
||||
using T = std::numeric_limits<To>;
|
||||
static_assert(std::is_floating_point<From>::value, "From must be floating");
|
||||
static_assert(std::is_floating_point<To>::value, "To must be floating");
|
||||
|
||||
// catch the only happy case
|
||||
if (std::isfinite(from)) {
|
||||
if (from >= T::lowest() && from <= T::max()) {
|
||||
return static_cast<To>(from);
|
||||
}
|
||||
// not within range.
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
|
||||
// nan and inf will be preserved
|
||||
return static_cast<To>(from);
|
||||
} // function
|
||||
|
||||
template <typename To, typename From,
|
||||
FMT_ENABLE_IF(std::is_same<From, To>::value)>
|
||||
FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) {
|
||||
ec = 0;
|
||||
static_assert(std::is_floating_point<From>::value, "From must be floating");
|
||||
return from;
|
||||
}
|
||||
|
||||
/**
|
||||
* safe duration cast between integral durations
|
||||
*/
|
||||
template <typename To, typename FromRep, typename FromPeriod,
|
||||
FMT_ENABLE_IF(std::is_integral<FromRep>::value),
|
||||
FMT_ENABLE_IF(std::is_integral<typename To::rep>::value)>
|
||||
To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
|
||||
int& ec) {
|
||||
using From = std::chrono::duration<FromRep, FromPeriod>;
|
||||
ec = 0;
|
||||
// the basic idea is that we need to convert from count() in the from type
|
||||
// to count() in the To type, by multiplying it with this:
|
||||
struct Factor
|
||||
: std::ratio_divide<typename From::period, typename To::period> {};
|
||||
|
||||
static_assert(Factor::num > 0, "num must be positive");
|
||||
static_assert(Factor::den > 0, "den must be positive");
|
||||
|
||||
// the conversion is like this: multiply from.count() with Factor::num
|
||||
// /Factor::den and convert it to To::rep, all this without
|
||||
// overflow/underflow. let's start by finding a suitable type that can hold
|
||||
// both To, From and Factor::num
|
||||
using IntermediateRep =
|
||||
typename std::common_type<typename From::rep, typename To::rep,
|
||||
decltype(Factor::num)>::type;
|
||||
|
||||
// safe conversion to IntermediateRep
|
||||
IntermediateRep count =
|
||||
lossless_integral_conversion<IntermediateRep>(from.count(), ec);
|
||||
if (ec) {
|
||||
return {};
|
||||
}
|
||||
// multiply with Factor::num without overflow or underflow
|
||||
if (Factor::num != 1) {
|
||||
const auto max1 = internal::max_value<IntermediateRep>() / Factor::num;
|
||||
if (count > max1) {
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
const auto min1 = std::numeric_limits<IntermediateRep>::min() / Factor::num;
|
||||
if (count < min1) {
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
count *= Factor::num;
|
||||
}
|
||||
|
||||
// this can't go wrong, right? den>0 is checked earlier.
|
||||
if (Factor::den != 1) {
|
||||
count /= Factor::den;
|
||||
}
|
||||
// convert to the to type, safely
|
||||
using ToRep = typename To::rep;
|
||||
const ToRep tocount = lossless_integral_conversion<ToRep>(count, ec);
|
||||
if (ec) {
|
||||
return {};
|
||||
}
|
||||
return To{tocount};
|
||||
}
|
||||
|
||||
/**
|
||||
* safe duration_cast between floating point durations
|
||||
*/
|
||||
template <typename To, typename FromRep, typename FromPeriod,
|
||||
FMT_ENABLE_IF(std::is_floating_point<FromRep>::value),
|
||||
FMT_ENABLE_IF(std::is_floating_point<typename To::rep>::value)>
|
||||
To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
|
||||
int& ec) {
|
||||
using From = std::chrono::duration<FromRep, FromPeriod>;
|
||||
ec = 0;
|
||||
if (std::isnan(from.count())) {
|
||||
// nan in, gives nan out. easy.
|
||||
return To{std::numeric_limits<typename To::rep>::quiet_NaN()};
|
||||
}
|
||||
// maybe we should also check if from is denormal, and decide what to do about
|
||||
// it.
|
||||
|
||||
// +-inf should be preserved.
|
||||
if (std::isinf(from.count())) {
|
||||
return To{from.count()};
|
||||
}
|
||||
|
||||
// the basic idea is that we need to convert from count() in the from type
|
||||
// to count() in the To type, by multiplying it with this:
|
||||
struct Factor
|
||||
: std::ratio_divide<typename From::period, typename To::period> {};
|
||||
|
||||
static_assert(Factor::num > 0, "num must be positive");
|
||||
static_assert(Factor::den > 0, "den must be positive");
|
||||
|
||||
// the conversion is like this: multiply from.count() with Factor::num
|
||||
// /Factor::den and convert it to To::rep, all this without
|
||||
// overflow/underflow. let's start by finding a suitable type that can hold
|
||||
// both To, From and Factor::num
|
||||
using IntermediateRep =
|
||||
typename std::common_type<typename From::rep, typename To::rep,
|
||||
decltype(Factor::num)>::type;
|
||||
|
||||
// force conversion of From::rep -> IntermediateRep to be safe,
|
||||
// even if it will never happen be narrowing in this context.
|
||||
IntermediateRep count =
|
||||
safe_float_conversion<IntermediateRep>(from.count(), ec);
|
||||
if (ec) {
|
||||
return {};
|
||||
}
|
||||
|
||||
// multiply with Factor::num without overflow or underflow
|
||||
if (Factor::num != 1) {
|
||||
constexpr auto max1 = internal::max_value<IntermediateRep>() /
|
||||
static_cast<IntermediateRep>(Factor::num);
|
||||
if (count > max1) {
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
constexpr auto min1 = std::numeric_limits<IntermediateRep>::lowest() /
|
||||
static_cast<IntermediateRep>(Factor::num);
|
||||
if (count < min1) {
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
count *= static_cast<IntermediateRep>(Factor::num);
|
||||
}
|
||||
|
||||
// this can't go wrong, right? den>0 is checked earlier.
|
||||
if (Factor::den != 1) {
|
||||
using common_t = typename std::common_type<IntermediateRep, intmax_t>::type;
|
||||
count /= static_cast<common_t>(Factor::den);
|
||||
}
|
||||
|
||||
// convert to the to type, safely
|
||||
using ToRep = typename To::rep;
|
||||
|
||||
const ToRep tocount = safe_float_conversion<ToRep>(count, ec);
|
||||
if (ec) {
|
||||
return {};
|
||||
}
|
||||
return To{tocount};
|
||||
}
|
||||
} // namespace safe_duration_cast
|
||||
#endif
|
||||
|
||||
// Prevents expansion of a preceding token as a function-style macro.
|
||||
// Usage: f FMT_NOMACRO()
|
||||
@@ -220,12 +495,12 @@ FMT_CONSTEXPR const Char* parse_chrono_format(const Char* begin,
|
||||
handler.on_text(ptr - 1, ptr);
|
||||
break;
|
||||
case 'n': {
|
||||
const char newline[] = "\n";
|
||||
const Char newline[] = {'\n'};
|
||||
handler.on_text(newline, newline + 1);
|
||||
break;
|
||||
}
|
||||
case 't': {
|
||||
const char tab[] = "\t";
|
||||
const Char tab[] = {'\t'};
|
||||
handler.on_text(tab, tab + 1);
|
||||
break;
|
||||
}
|
||||
@@ -403,7 +678,7 @@ inline bool isfinite(T value) {
|
||||
return std::isfinite(value);
|
||||
}
|
||||
|
||||
// Convers value to int and checks that it's in the range [0, upper).
|
||||
// Converts value to int and checks that it's in the range [0, upper).
|
||||
template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
|
||||
inline int to_nonnegative_int(T value, int upper) {
|
||||
FMT_ASSERT(value >= 0 && value <= upper, "invalid value");
|
||||
@@ -421,7 +696,7 @@ inline int to_nonnegative_int(T value, int upper) {
|
||||
|
||||
template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
|
||||
inline T mod(T x, int y) {
|
||||
return x % y;
|
||||
return x % static_cast<T>(y);
|
||||
}
|
||||
template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
|
||||
inline T mod(T x, int y) {
|
||||
@@ -484,18 +759,30 @@ inline std::chrono::duration<Rep, std::milli> get_milliseconds(
|
||||
return std::chrono::duration<Rep, std::milli>(static_cast<Rep>(ms));
|
||||
}
|
||||
|
||||
template <typename Rep, typename OutputIt>
|
||||
OutputIt format_chrono_duration_value(OutputIt out, Rep val, int precision) {
|
||||
if (precision >= 0) return format_to(out, "{:.{}f}", val, precision);
|
||||
return format_to(out, std::is_floating_point<Rep>::value ? "{:g}" : "{}",
|
||||
template <typename Char, typename Rep, typename OutputIt>
|
||||
OutputIt format_duration_value(OutputIt out, Rep val, int precision) {
|
||||
const Char pr_f[] = {'{', ':', '.', '{', '}', 'f', '}', 0};
|
||||
if (precision >= 0) return format_to(out, pr_f, val, precision);
|
||||
const Char fp_f[] = {'{', ':', 'g', '}', 0};
|
||||
const Char format[] = {'{', '}', 0};
|
||||
return format_to(out, std::is_floating_point<Rep>::value ? fp_f : format,
|
||||
val);
|
||||
}
|
||||
|
||||
template <typename Period, typename OutputIt>
|
||||
static OutputIt format_chrono_duration_unit(OutputIt out) {
|
||||
if (const char* unit = get_units<Period>()) return format_to(out, "{}", unit);
|
||||
if (Period::den == 1) return format_to(out, "[{}]s", Period::num);
|
||||
return format_to(out, "[{}/{}]s", Period::num, Period::den);
|
||||
template <typename Char, typename Period, typename OutputIt>
|
||||
OutputIt format_duration_unit(OutputIt out) {
|
||||
if (const char* unit = get_units<Period>()) {
|
||||
string_view s(unit);
|
||||
if (const_check(std::is_same<Char, wchar_t>())) {
|
||||
utf8_to_utf16 u(s);
|
||||
return std::copy(u.c_str(), u.c_str() + u.size(), out);
|
||||
}
|
||||
return std::copy(s.begin(), s.end(), out);
|
||||
}
|
||||
const Char num_f[] = {'[', '{', '}', ']', 's', 0};
|
||||
if (Period::den == 1) return format_to(out, num_f, Period::num);
|
||||
const Char num_def_f[] = {'[', '{', '}', '/', '{', '}', ']', 's', 0};
|
||||
return format_to(out, num_def_f, Period::num, Period::den);
|
||||
}
|
||||
|
||||
template <typename FormatContext, typename OutputIt, typename Rep,
|
||||
@@ -518,7 +805,10 @@ struct chrono_formatter {
|
||||
|
||||
explicit chrono_formatter(FormatContext& ctx, OutputIt o,
|
||||
std::chrono::duration<Rep, Period> d)
|
||||
: context(ctx), out(o), val(d.count()), negative(false) {
|
||||
: context(ctx),
|
||||
out(o),
|
||||
val(static_cast<rep>(d.count())),
|
||||
negative(false) {
|
||||
if (d.count() < 0) {
|
||||
val = 0 - val;
|
||||
negative = true;
|
||||
@@ -582,8 +872,8 @@ struct chrono_formatter {
|
||||
void write(Rep value, int width) {
|
||||
write_sign();
|
||||
if (isnan(value)) return write_nan();
|
||||
uint32_or_64_t<int> n = to_unsigned(
|
||||
to_nonnegative_int(value, (std::numeric_limits<int>::max)()));
|
||||
uint32_or_64_or_128_t<int> n =
|
||||
to_unsigned(to_nonnegative_int(value, max_value<int>()));
|
||||
int num_digits = internal::count_digits(n);
|
||||
if (width > num_digits) out = std::fill_n(out, width - num_digits, '0');
|
||||
out = format_decimal<char_type>(out, n, num_digits);
|
||||
@@ -593,13 +883,13 @@ struct chrono_formatter {
|
||||
void write_pinf() { std::copy_n("inf", 3, out); }
|
||||
void write_ninf() { std::copy_n("-inf", 4, out); }
|
||||
|
||||
void format_localized(const tm& time, const char* format) {
|
||||
void format_localized(const tm& time, char format, char modifier = 0) {
|
||||
if (isnan(val)) return write_nan();
|
||||
auto locale = context.locale().template get<std::locale>();
|
||||
auto& facet = std::use_facet<std::time_put<char_type>>(locale);
|
||||
std::basic_ostringstream<char_type> os;
|
||||
os.imbue(locale);
|
||||
facet.put(os, os, ' ', &time, format, format + std::strlen(format));
|
||||
facet.put(os, os, ' ', &time, format, modifier);
|
||||
auto str = os.str();
|
||||
std::copy(str.begin(), str.end(), out);
|
||||
}
|
||||
@@ -629,7 +919,7 @@ struct chrono_formatter {
|
||||
if (ns == numeric_system::standard) return write(hour(), 2);
|
||||
auto time = tm();
|
||||
time.tm_hour = to_nonnegative_int(hour(), 24);
|
||||
format_localized(time, "%OH");
|
||||
format_localized(time, 'H', 'O');
|
||||
}
|
||||
|
||||
void on_12_hour(numeric_system ns) {
|
||||
@@ -638,7 +928,7 @@ struct chrono_formatter {
|
||||
if (ns == numeric_system::standard) return write(hour12(), 2);
|
||||
auto time = tm();
|
||||
time.tm_hour = to_nonnegative_int(hour12(), 12);
|
||||
format_localized(time, "%OI");
|
||||
format_localized(time, 'I', 'O');
|
||||
}
|
||||
|
||||
void on_minute(numeric_system ns) {
|
||||
@@ -647,7 +937,7 @@ struct chrono_formatter {
|
||||
if (ns == numeric_system::standard) return write(minute(), 2);
|
||||
auto time = tm();
|
||||
time.tm_min = to_nonnegative_int(minute(), 60);
|
||||
format_localized(time, "%OM");
|
||||
format_localized(time, 'M', 'O');
|
||||
}
|
||||
|
||||
void on_second(numeric_system ns) {
|
||||
@@ -672,13 +962,12 @@ struct chrono_formatter {
|
||||
}
|
||||
auto time = tm();
|
||||
time.tm_sec = to_nonnegative_int(second(), 60);
|
||||
format_localized(time, "%OS");
|
||||
format_localized(time, 'S', 'O');
|
||||
}
|
||||
|
||||
void on_12_hour_time() {
|
||||
if (handle_nan_inf()) return;
|
||||
|
||||
format_localized(time(), "%r");
|
||||
format_localized(time(), 'r');
|
||||
}
|
||||
|
||||
void on_24_hour_time() {
|
||||
@@ -702,16 +991,18 @@ struct chrono_formatter {
|
||||
|
||||
void on_am_pm() {
|
||||
if (handle_nan_inf()) return;
|
||||
format_localized(time(), "%p");
|
||||
format_localized(time(), 'p');
|
||||
}
|
||||
|
||||
void on_duration_value() {
|
||||
if (handle_nan_inf()) return;
|
||||
write_sign();
|
||||
out = format_chrono_duration_value(out, val, precision);
|
||||
out = format_duration_value<char_type>(out, val, precision);
|
||||
}
|
||||
|
||||
void on_duration_unit() { out = format_chrono_duration_unit<Period>(out); }
|
||||
void on_duration_unit() {
|
||||
out = format_duration_unit<char_type, Period>(out);
|
||||
}
|
||||
};
|
||||
} // namespace internal
|
||||
|
||||
@@ -728,7 +1019,7 @@ struct formatter<std::chrono::duration<Rep, Period>, Char> {
|
||||
|
||||
struct spec_handler {
|
||||
formatter& f;
|
||||
basic_parse_context<Char>& context;
|
||||
basic_format_parse_context<Char>& context;
|
||||
basic_string_view<Char> format_str;
|
||||
|
||||
template <typename Id> FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) {
|
||||
@@ -738,8 +1029,7 @@ struct formatter<std::chrono::duration<Rep, Period>, Char> {
|
||||
|
||||
FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view<Char> arg_id) {
|
||||
context.check_arg_id(arg_id);
|
||||
const auto str_val = internal::string_view_metadata(format_str, arg_id);
|
||||
return arg_ref_type(str_val);
|
||||
return arg_ref_type(arg_id);
|
||||
}
|
||||
|
||||
FMT_CONSTEXPR arg_ref_type make_arg_ref(internal::auto_id) {
|
||||
@@ -747,10 +1037,10 @@ struct formatter<std::chrono::duration<Rep, Period>, Char> {
|
||||
}
|
||||
|
||||
void on_error(const char* msg) { FMT_THROW(format_error(msg)); }
|
||||
void on_fill(Char fill) { f.specs.fill[0] = fill; }
|
||||
void on_fill(basic_string_view<Char> fill) { f.specs.fill = fill; }
|
||||
void on_align(align_t align) { f.specs.align = align; }
|
||||
void on_width(unsigned width) { f.specs.width = width; }
|
||||
void on_precision(unsigned precision) { f.precision = precision; }
|
||||
void on_width(int width) { f.specs.width = width; }
|
||||
void on_precision(int _precision) { f.precision = _precision; }
|
||||
void end_precision() {}
|
||||
|
||||
template <typename Id> void on_dynamic_width(Id arg_id) {
|
||||
@@ -762,13 +1052,13 @@ struct formatter<std::chrono::duration<Rep, Period>, Char> {
|
||||
}
|
||||
};
|
||||
|
||||
using iterator = typename basic_parse_context<Char>::iterator;
|
||||
using iterator = typename basic_format_parse_context<Char>::iterator;
|
||||
struct parse_range {
|
||||
iterator begin;
|
||||
iterator end;
|
||||
};
|
||||
|
||||
FMT_CONSTEXPR parse_range do_parse(basic_parse_context<Char>& ctx) {
|
||||
FMT_CONSTEXPR parse_range do_parse(basic_format_parse_context<Char>& ctx) {
|
||||
auto begin = ctx.begin(), end = ctx.end();
|
||||
if (begin == end || *begin == '}') return {begin, begin};
|
||||
spec_handler handler{*this, ctx, format_str};
|
||||
@@ -789,7 +1079,7 @@ struct formatter<std::chrono::duration<Rep, Period>, Char> {
|
||||
public:
|
||||
formatter() : precision(-1) {}
|
||||
|
||||
FMT_CONSTEXPR auto parse(basic_parse_context<Char>& ctx)
|
||||
FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx)
|
||||
-> decltype(ctx.begin()) {
|
||||
auto range = do_parse(ctx);
|
||||
format_str = basic_string_view<Char>(
|
||||
@@ -806,13 +1096,13 @@ struct formatter<std::chrono::duration<Rep, Period>, Char> {
|
||||
auto out = std::back_inserter(buf);
|
||||
using range = internal::output_range<decltype(ctx.out()), Char>;
|
||||
internal::basic_writer<range> w(range(ctx.out()));
|
||||
internal::handle_dynamic_spec<internal::width_checker>(
|
||||
specs.width, width_ref, ctx, format_str.begin());
|
||||
internal::handle_dynamic_spec<internal::width_checker>(specs.width,
|
||||
width_ref, ctx);
|
||||
internal::handle_dynamic_spec<internal::precision_checker>(
|
||||
precision, precision_ref, ctx, format_str.begin());
|
||||
precision, precision_ref, ctx);
|
||||
if (begin == end || *begin == '}') {
|
||||
out = internal::format_chrono_duration_value(out, d.count(), precision);
|
||||
internal::format_chrono_duration_unit<Period>(out);
|
||||
out = internal::format_duration_value<Char>(out, d.count(), precision);
|
||||
internal::format_duration_unit<Char, Period>(out);
|
||||
} else {
|
||||
internal::chrono_formatter<FormatContext, decltype(out), Rep, Period> f(
|
||||
ctx, out, d);
|
||||
|
@@ -299,15 +299,15 @@ class text_style {
|
||||
return static_cast<uint8_t>(ems) != 0;
|
||||
}
|
||||
FMT_CONSTEXPR internal::color_type get_foreground() const FMT_NOEXCEPT {
|
||||
assert(has_foreground() && "no foreground specified for this style");
|
||||
FMT_ASSERT(has_foreground(), "no foreground specified for this style");
|
||||
return foreground_color;
|
||||
}
|
||||
FMT_CONSTEXPR internal::color_type get_background() const FMT_NOEXCEPT {
|
||||
assert(has_background() && "no background specified for this style");
|
||||
FMT_ASSERT(has_background(), "no background specified for this style");
|
||||
return background_color;
|
||||
}
|
||||
FMT_CONSTEXPR emphasis get_emphasis() const FMT_NOEXCEPT {
|
||||
assert(has_emphasis() && "no emphasis specified for this style");
|
||||
FMT_ASSERT(has_emphasis(), "no emphasis specified for this style");
|
||||
return ems;
|
||||
}
|
||||
|
||||
@@ -412,7 +412,7 @@ template <typename Char> struct ansi_color_escape {
|
||||
|
||||
FMT_CONSTEXPR const Char* begin() const FMT_NOEXCEPT { return buffer; }
|
||||
FMT_CONSTEXPR const Char* end() const FMT_NOEXCEPT {
|
||||
return buffer + std::strlen(buffer);
|
||||
return buffer + std::char_traits<Char>::length(buffer);
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -470,58 +470,39 @@ inline void reset_color(basic_memory_buffer<Char>& buffer) FMT_NOEXCEPT {
|
||||
}
|
||||
|
||||
template <typename Char>
|
||||
std::basic_string<Char> vformat(const text_style& ts,
|
||||
basic_string_view<Char> format_str,
|
||||
basic_format_args<buffer_context<Char> > args) {
|
||||
basic_memory_buffer<Char> buffer;
|
||||
void vformat_to(basic_memory_buffer<Char>& buf, const text_style& ts,
|
||||
basic_string_view<Char> format_str,
|
||||
basic_format_args<buffer_context<Char>> args) {
|
||||
bool has_style = false;
|
||||
if (ts.has_emphasis()) {
|
||||
has_style = true;
|
||||
ansi_color_escape<Char> escape = make_emphasis<Char>(ts.get_emphasis());
|
||||
buffer.append(escape.begin(), escape.end());
|
||||
auto emphasis = internal::make_emphasis<Char>(ts.get_emphasis());
|
||||
buf.append(emphasis.begin(), emphasis.end());
|
||||
}
|
||||
if (ts.has_foreground()) {
|
||||
has_style = true;
|
||||
ansi_color_escape<Char> escape =
|
||||
make_foreground_color<Char>(ts.get_foreground());
|
||||
buffer.append(escape.begin(), escape.end());
|
||||
auto foreground =
|
||||
internal::make_foreground_color<Char>(ts.get_foreground());
|
||||
buf.append(foreground.begin(), foreground.end());
|
||||
}
|
||||
if (ts.has_background()) {
|
||||
has_style = true;
|
||||
ansi_color_escape<Char> escape =
|
||||
make_background_color<Char>(ts.get_background());
|
||||
buffer.append(escape.begin(), escape.end());
|
||||
auto background =
|
||||
internal::make_background_color<Char>(ts.get_background());
|
||||
buf.append(background.begin(), background.end());
|
||||
}
|
||||
internal::vformat_to(buffer, format_str, args);
|
||||
if (has_style) {
|
||||
reset_color<Char>(buffer);
|
||||
}
|
||||
return fmt::to_string(buffer);
|
||||
internal::vformat_to(buf, format_str, args);
|
||||
if (has_style) internal::reset_color<Char>(buf);
|
||||
}
|
||||
} // namespace internal
|
||||
|
||||
template <typename S, typename Char = char_t<S> >
|
||||
template <typename S, typename Char = char_t<S>>
|
||||
void vprint(std::FILE* f, const text_style& ts, const S& format,
|
||||
basic_format_args<buffer_context<Char> > args) {
|
||||
bool has_style = false;
|
||||
if (ts.has_emphasis()) {
|
||||
has_style = true;
|
||||
internal::fputs<Char>(internal::make_emphasis<Char>(ts.get_emphasis()), f);
|
||||
}
|
||||
if (ts.has_foreground()) {
|
||||
has_style = true;
|
||||
internal::fputs<Char>(
|
||||
internal::make_foreground_color<Char>(ts.get_foreground()), f);
|
||||
}
|
||||
if (ts.has_background()) {
|
||||
has_style = true;
|
||||
internal::fputs<Char>(
|
||||
internal::make_background_color<Char>(ts.get_background()), f);
|
||||
}
|
||||
vprint(f, format, args);
|
||||
if (has_style) {
|
||||
internal::reset_color<Char>(f);
|
||||
}
|
||||
basic_format_args<buffer_context<Char>> args) {
|
||||
basic_memory_buffer<Char> buf;
|
||||
internal::vformat_to(buf, ts, to_string_view(format), args);
|
||||
buf.push_back(Char(0));
|
||||
internal::fputs(buf.data(), f);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -536,7 +517,7 @@ template <typename S, typename... Args,
|
||||
void print(std::FILE* f, const text_style& ts, const S& format_str,
|
||||
const Args&... args) {
|
||||
internal::check_format_string<Args...>(format_str);
|
||||
using context = buffer_context<char_t<S> >;
|
||||
using context = buffer_context<char_t<S>>;
|
||||
format_arg_store<context, Args...> as{args...};
|
||||
vprint(f, ts, format_str, basic_format_args<context>(as));
|
||||
}
|
||||
@@ -554,11 +535,13 @@ void print(const text_style& ts, const S& format_str, const Args&... args) {
|
||||
return print(stdout, ts, format_str, args...);
|
||||
}
|
||||
|
||||
template <typename S, typename Char = char_t<S> >
|
||||
template <typename S, typename Char = char_t<S>>
|
||||
inline std::basic_string<Char> vformat(
|
||||
const text_style& ts, const S& format_str,
|
||||
basic_format_args<buffer_context<Char> > args) {
|
||||
return internal::vformat(ts, to_string_view(format_str), args);
|
||||
basic_format_args<buffer_context<type_identity_t<Char>>> args) {
|
||||
basic_memory_buffer<Char> buf;
|
||||
internal::vformat_to(buf, ts, to_string_view(format_str), args);
|
||||
return fmt::to_string(buf);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -573,11 +556,11 @@ inline std::basic_string<Char> vformat(
|
||||
"The answer is {}", 42);
|
||||
\endrst
|
||||
*/
|
||||
template <typename S, typename... Args, typename Char = char_t<S> >
|
||||
template <typename S, typename... Args, typename Char = char_t<S>>
|
||||
inline std::basic_string<Char> format(const text_style& ts, const S& format_str,
|
||||
const Args&... args) {
|
||||
return internal::vformat(ts, to_string_view(format_str),
|
||||
{internal::make_args_checked(format_str, args...)});
|
||||
return vformat(ts, to_string_view(format_str),
|
||||
internal::make_args_checked<Args...>(format_str, args...));
|
||||
}
|
||||
|
||||
FMT_END_NAMESPACE
|
||||
|
@@ -9,255 +9,50 @@
|
||||
#define FMT_COMPILE_H_
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "format.h"
|
||||
|
||||
FMT_BEGIN_NAMESPACE
|
||||
namespace internal {
|
||||
|
||||
// Part of a compiled format string. It can be either literal text or a
|
||||
// replacement field.
|
||||
template <typename Char> struct format_part {
|
||||
public:
|
||||
struct named_argument_id {
|
||||
FMT_CONSTEXPR named_argument_id(internal::string_view_metadata id)
|
||||
: id(id) {}
|
||||
internal::string_view_metadata id;
|
||||
enum class kind { arg_index, arg_name, text, replacement };
|
||||
|
||||
struct replacement {
|
||||
arg_ref<Char> arg_id;
|
||||
dynamic_format_specs<Char> specs;
|
||||
};
|
||||
|
||||
struct argument_id {
|
||||
FMT_CONSTEXPR argument_id() : argument_id(0u) {}
|
||||
|
||||
FMT_CONSTEXPR argument_id(unsigned id)
|
||||
: which(which_arg_id::index), val(id) {}
|
||||
|
||||
FMT_CONSTEXPR argument_id(internal::string_view_metadata id)
|
||||
: which(which_arg_id::named_index), val(id) {}
|
||||
|
||||
enum class which_arg_id { index, named_index };
|
||||
|
||||
which_arg_id which;
|
||||
|
||||
union value {
|
||||
FMT_CONSTEXPR value() : index(0u) {}
|
||||
FMT_CONSTEXPR value(unsigned id) : index(id) {}
|
||||
FMT_CONSTEXPR value(internal::string_view_metadata id)
|
||||
: named_index(id) {}
|
||||
|
||||
unsigned index;
|
||||
internal::string_view_metadata named_index;
|
||||
} val;
|
||||
};
|
||||
|
||||
struct specification {
|
||||
FMT_CONSTEXPR specification() : arg_id(0u) {}
|
||||
FMT_CONSTEXPR specification(unsigned id) : arg_id(id) {}
|
||||
|
||||
FMT_CONSTEXPR specification(internal::string_view_metadata id)
|
||||
: arg_id(id) {}
|
||||
|
||||
argument_id arg_id;
|
||||
internal::dynamic_format_specs<Char> parsed_specs;
|
||||
};
|
||||
|
||||
FMT_CONSTEXPR format_part()
|
||||
: which(kind::argument_id), end_of_argument_id(0u), val(0u) {}
|
||||
|
||||
FMT_CONSTEXPR format_part(internal::string_view_metadata text)
|
||||
: which(kind::text), end_of_argument_id(0u), val(text) {}
|
||||
|
||||
FMT_CONSTEXPR format_part(unsigned id)
|
||||
: which(kind::argument_id), end_of_argument_id(0u), val(id) {}
|
||||
|
||||
FMT_CONSTEXPR format_part(named_argument_id arg_id)
|
||||
: which(kind::named_argument_id), end_of_argument_id(0u), val(arg_id) {}
|
||||
|
||||
FMT_CONSTEXPR format_part(specification spec)
|
||||
: which(kind::specification), end_of_argument_id(0u), val(spec) {}
|
||||
|
||||
enum class kind { argument_id, named_argument_id, text, specification };
|
||||
|
||||
kind which;
|
||||
std::size_t end_of_argument_id;
|
||||
kind part_kind;
|
||||
union value {
|
||||
FMT_CONSTEXPR value() : arg_id(0u) {}
|
||||
FMT_CONSTEXPR value(unsigned id) : arg_id(id) {}
|
||||
FMT_CONSTEXPR value(named_argument_id named_id)
|
||||
: named_arg_id(named_id.id) {}
|
||||
FMT_CONSTEXPR value(internal::string_view_metadata t) : text(t) {}
|
||||
FMT_CONSTEXPR value(specification s) : spec(s) {}
|
||||
unsigned arg_id;
|
||||
internal::string_view_metadata named_arg_id;
|
||||
internal::string_view_metadata text;
|
||||
specification spec;
|
||||
int arg_index;
|
||||
basic_string_view<Char> str;
|
||||
replacement repl;
|
||||
|
||||
FMT_CONSTEXPR value(int index = 0) : arg_index(index) {}
|
||||
FMT_CONSTEXPR value(basic_string_view<Char> s) : str(s) {}
|
||||
FMT_CONSTEXPR value(replacement r) : repl(r) {}
|
||||
} val;
|
||||
};
|
||||
// Position past the end of the argument id.
|
||||
const Char* arg_id_end = nullptr;
|
||||
|
||||
template <typename Char, typename PartsContainer>
|
||||
class format_preparation_handler : public internal::error_handler {
|
||||
private:
|
||||
using part = format_part<Char>;
|
||||
FMT_CONSTEXPR format_part(kind k = kind::arg_index, value v = {})
|
||||
: part_kind(k), val(v) {}
|
||||
|
||||
public:
|
||||
using iterator = typename basic_string_view<Char>::iterator;
|
||||
|
||||
FMT_CONSTEXPR format_preparation_handler(basic_string_view<Char> format,
|
||||
PartsContainer& parts)
|
||||
: parts_(parts), format_(format), parse_context_(format) {}
|
||||
|
||||
FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) {
|
||||
if (begin == end) return;
|
||||
const auto offset = begin - format_.data();
|
||||
const auto size = end - begin;
|
||||
parts_.push_back(part(string_view_metadata(offset, size)));
|
||||
static FMT_CONSTEXPR format_part make_arg_index(int index) {
|
||||
return format_part(kind::arg_index, index);
|
||||
}
|
||||
|
||||
FMT_CONSTEXPR void on_arg_id() {
|
||||
parts_.push_back(part(parse_context_.next_arg_id()));
|
||||
static FMT_CONSTEXPR format_part make_arg_name(basic_string_view<Char> name) {
|
||||
return format_part(kind::arg_name, name);
|
||||
}
|
||||
|
||||
FMT_CONSTEXPR void on_arg_id(unsigned id) {
|
||||
parse_context_.check_arg_id(id);
|
||||
parts_.push_back(part(id));
|
||||
static FMT_CONSTEXPR format_part make_text(basic_string_view<Char> text) {
|
||||
return format_part(kind::text, text);
|
||||
}
|
||||
|
||||
FMT_CONSTEXPR void on_arg_id(basic_string_view<Char> id) {
|
||||
const auto view = string_view_metadata(format_, id);
|
||||
const auto arg_id = typename part::named_argument_id(view);
|
||||
parts_.push_back(part(arg_id));
|
||||
static FMT_CONSTEXPR format_part make_replacement(replacement repl) {
|
||||
return format_part(kind::replacement, repl);
|
||||
}
|
||||
|
||||
FMT_CONSTEXPR void on_replacement_field(const Char* ptr) {
|
||||
parts_.back().end_of_argument_id = ptr - format_.begin();
|
||||
}
|
||||
|
||||
FMT_CONSTEXPR const Char* on_format_specs(const Char* begin,
|
||||
const Char* end) {
|
||||
const auto specs_offset = to_unsigned(begin - format_.begin());
|
||||
|
||||
using parse_context = basic_parse_context<Char>;
|
||||
internal::dynamic_format_specs<Char> parsed_specs;
|
||||
dynamic_specs_handler<parse_context> handler(parsed_specs, parse_context_);
|
||||
begin = parse_format_specs(begin, end, handler);
|
||||
|
||||
if (*begin != '}') on_error("missing '}' in format string");
|
||||
|
||||
auto& last_part = parts_.back();
|
||||
auto specs = last_part.which == part::kind::argument_id
|
||||
? typename part::specification(last_part.val.arg_id)
|
||||
: typename part::specification(last_part.val.named_arg_id);
|
||||
specs.parsed_specs = parsed_specs;
|
||||
last_part = part(specs);
|
||||
last_part.end_of_argument_id = specs_offset;
|
||||
return begin;
|
||||
}
|
||||
|
||||
private:
|
||||
PartsContainer& parts_;
|
||||
basic_string_view<Char> format_;
|
||||
basic_parse_context<Char> parse_context_;
|
||||
};
|
||||
|
||||
template <typename Format, typename PreparedPartsProvider, typename... Args>
|
||||
class prepared_format {
|
||||
public:
|
||||
using char_type = char_t<Format>;
|
||||
using format_part_t = format_part<char_type>;
|
||||
|
||||
constexpr prepared_format(Format f)
|
||||
: format_(std::move(f)), parts_provider_(to_string_view(format_)) {}
|
||||
|
||||
prepared_format() = delete;
|
||||
|
||||
using context = buffer_context<char_type>;
|
||||
|
||||
template <typename Range, typename Context>
|
||||
auto vformat_to(Range out, basic_format_args<Context> args) const ->
|
||||
typename Context::iterator {
|
||||
const auto format_view = internal::to_string_view(format_);
|
||||
basic_parse_context<char_type> parse_ctx(format_view);
|
||||
Context ctx(out.begin(), args);
|
||||
|
||||
const auto& parts = parts_provider_.parts();
|
||||
for (auto part_it = parts.begin(); part_it != parts.end(); ++part_it) {
|
||||
const auto& part = *part_it;
|
||||
const auto& value = part.val;
|
||||
|
||||
switch (part.which) {
|
||||
case format_part_t::kind::text: {
|
||||
const auto text = value.text.to_view(format_view.data());
|
||||
auto output = ctx.out();
|
||||
auto&& it = internal::reserve(output, text.size());
|
||||
it = std::copy_n(text.begin(), text.size(), it);
|
||||
ctx.advance_to(output);
|
||||
} break;
|
||||
|
||||
case format_part_t::kind::argument_id: {
|
||||
advance_parse_context_to_specification(parse_ctx, part);
|
||||
format_arg<Range>(parse_ctx, ctx, value.arg_id);
|
||||
} break;
|
||||
|
||||
case format_part_t::kind::named_argument_id: {
|
||||
advance_parse_context_to_specification(parse_ctx, part);
|
||||
const auto named_arg_id =
|
||||
value.named_arg_id.to_view(format_view.data());
|
||||
format_arg<Range>(parse_ctx, ctx, named_arg_id);
|
||||
} break;
|
||||
case format_part_t::kind::specification: {
|
||||
const auto& arg_id_value = value.spec.arg_id.val;
|
||||
const auto arg = value.spec.arg_id.which ==
|
||||
format_part_t::argument_id::which_arg_id::index
|
||||
? ctx.arg(arg_id_value.index)
|
||||
: ctx.arg(arg_id_value.named_index.to_view(
|
||||
to_string_view(format_).data()));
|
||||
|
||||
auto specs = value.spec.parsed_specs;
|
||||
|
||||
handle_dynamic_spec<internal::width_checker>(
|
||||
specs.width, specs.width_ref, ctx, format_view.begin());
|
||||
handle_dynamic_spec<internal::precision_checker>(
|
||||
specs.precision, specs.precision_ref, ctx, format_view.begin());
|
||||
|
||||
check_prepared_specs(specs, arg.type());
|
||||
advance_parse_context_to_specification(parse_ctx, part);
|
||||
ctx.advance_to(
|
||||
visit_format_arg(arg_formatter<Range>(ctx, nullptr, &specs), arg));
|
||||
} break;
|
||||
}
|
||||
}
|
||||
|
||||
return ctx.out();
|
||||
}
|
||||
|
||||
private:
|
||||
void advance_parse_context_to_specification(
|
||||
basic_parse_context<char_type>& parse_ctx,
|
||||
const format_part_t& part) const {
|
||||
const auto view = to_string_view(format_);
|
||||
const auto specification_begin = view.data() + part.end_of_argument_id;
|
||||
advance_to(parse_ctx, specification_begin);
|
||||
}
|
||||
|
||||
template <typename Range, typename Context, typename Id>
|
||||
void format_arg(basic_parse_context<char_type>& parse_ctx, Context& ctx,
|
||||
Id arg_id) const {
|
||||
parse_ctx.check_arg_id(arg_id);
|
||||
const auto stopped_at =
|
||||
visit_format_arg(arg_formatter<Range>(ctx), ctx.arg(arg_id));
|
||||
ctx.advance_to(stopped_at);
|
||||
}
|
||||
|
||||
template <typename Char>
|
||||
void check_prepared_specs(const basic_format_specs<Char>& specs,
|
||||
internal::type arg_type) const {
|
||||
internal::error_handler h;
|
||||
numeric_specs_checker<internal::error_handler> checker(h, arg_type);
|
||||
if (specs.align == align::numeric) checker.require_numeric_argument();
|
||||
if (specs.sign != sign::none) checker.check_sign();
|
||||
if (specs.alt) checker.require_numeric_argument();
|
||||
if (specs.precision >= 0) checker.check_precision();
|
||||
}
|
||||
|
||||
private:
|
||||
Format format_;
|
||||
PreparedPartsProvider parts_provider_;
|
||||
};
|
||||
|
||||
template <typename Char> struct part_counter {
|
||||
@@ -268,7 +63,7 @@ template <typename Char> struct part_counter {
|
||||
}
|
||||
|
||||
FMT_CONSTEXPR void on_arg_id() { ++num_parts; }
|
||||
FMT_CONSTEXPR void on_arg_id(unsigned) { ++num_parts; }
|
||||
FMT_CONSTEXPR void on_arg_id(int) { ++num_parts; }
|
||||
FMT_CONSTEXPR void on_arg_id(basic_string_view<Char>) { ++num_parts; }
|
||||
|
||||
FMT_CONSTEXPR void on_replacement_field(const Char*) {}
|
||||
@@ -276,13 +71,13 @@ template <typename Char> struct part_counter {
|
||||
FMT_CONSTEXPR const Char* on_format_specs(const Char* begin,
|
||||
const Char* end) {
|
||||
// Find the matching brace.
|
||||
unsigned braces_counter = 0;
|
||||
unsigned brace_counter = 0;
|
||||
for (; begin != end; ++begin) {
|
||||
if (*begin == '{') {
|
||||
++braces_counter;
|
||||
++brace_counter;
|
||||
} else if (*begin == '}') {
|
||||
if (braces_counter == 0u) break;
|
||||
--braces_counter;
|
||||
if (brace_counter == 0u) break;
|
||||
--brace_counter;
|
||||
}
|
||||
}
|
||||
return begin;
|
||||
@@ -291,156 +86,493 @@ template <typename Char> struct part_counter {
|
||||
FMT_CONSTEXPR void on_error(const char*) {}
|
||||
};
|
||||
|
||||
template <typename Format> class compiletime_prepared_parts_type_provider {
|
||||
private:
|
||||
using char_type = char_t<Format>;
|
||||
// Counts the number of parts in a format string.
|
||||
template <typename Char>
|
||||
FMT_CONSTEXPR unsigned count_parts(basic_string_view<Char> format_str) {
|
||||
part_counter<Char> counter;
|
||||
parse_format_string<true>(format_str, counter);
|
||||
return counter.num_parts;
|
||||
}
|
||||
|
||||
static FMT_CONSTEXPR unsigned count_parts() {
|
||||
FMT_CONSTEXPR_DECL const auto text = to_string_view(Format{});
|
||||
part_counter<char_type> counter;
|
||||
internal::parse_format_string</*IS_CONSTEXPR=*/true>(text, counter);
|
||||
return counter.num_parts;
|
||||
template <typename Char, typename PartHandler>
|
||||
class format_string_compiler : public error_handler {
|
||||
private:
|
||||
using part = format_part<Char>;
|
||||
|
||||
PartHandler handler_;
|
||||
part part_;
|
||||
basic_string_view<Char> format_str_;
|
||||
basic_format_parse_context<Char> parse_context_;
|
||||
|
||||
public:
|
||||
FMT_CONSTEXPR format_string_compiler(basic_string_view<Char> format_str,
|
||||
PartHandler handler)
|
||||
: handler_(handler),
|
||||
format_str_(format_str),
|
||||
parse_context_(format_str) {}
|
||||
|
||||
FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) {
|
||||
if (begin != end)
|
||||
handler_(part::make_text({begin, to_unsigned(end - begin)}));
|
||||
}
|
||||
|
||||
// Workaround for old compilers. Compiletime parts preparation will not be
|
||||
// performed with them anyway.
|
||||
FMT_CONSTEXPR void on_arg_id() {
|
||||
part_ = part::make_arg_index(parse_context_.next_arg_id());
|
||||
}
|
||||
|
||||
FMT_CONSTEXPR void on_arg_id(int id) {
|
||||
parse_context_.check_arg_id(id);
|
||||
part_ = part::make_arg_index(id);
|
||||
}
|
||||
|
||||
FMT_CONSTEXPR void on_arg_id(basic_string_view<Char> id) {
|
||||
part_ = part::make_arg_name(id);
|
||||
}
|
||||
|
||||
FMT_CONSTEXPR void on_replacement_field(const Char* ptr) {
|
||||
part_.arg_id_end = ptr;
|
||||
handler_(part_);
|
||||
}
|
||||
|
||||
FMT_CONSTEXPR const Char* on_format_specs(const Char* begin,
|
||||
const Char* end) {
|
||||
auto repl = typename part::replacement();
|
||||
dynamic_specs_handler<basic_format_parse_context<Char>> handler(
|
||||
repl.specs, parse_context_);
|
||||
auto it = parse_format_specs(begin, end, handler);
|
||||
if (*it != '}') on_error("missing '}' in format string");
|
||||
repl.arg_id = part_.part_kind == part::kind::arg_index
|
||||
? arg_ref<Char>(part_.val.arg_index)
|
||||
: arg_ref<Char>(part_.val.str);
|
||||
auto part = part::make_replacement(repl);
|
||||
part.arg_id_end = begin;
|
||||
handler_(part);
|
||||
return it;
|
||||
}
|
||||
};
|
||||
|
||||
// Compiles a format string and invokes handler(part) for each parsed part.
|
||||
template <bool IS_CONSTEXPR, typename Char, typename PartHandler>
|
||||
FMT_CONSTEXPR void compile_format_string(basic_string_view<Char> format_str,
|
||||
PartHandler handler) {
|
||||
parse_format_string<IS_CONSTEXPR>(
|
||||
format_str,
|
||||
format_string_compiler<Char, PartHandler>(format_str, handler));
|
||||
}
|
||||
|
||||
template <typename Range, typename Context, typename Id>
|
||||
void format_arg(
|
||||
basic_format_parse_context<typename Range::value_type>& parse_ctx,
|
||||
Context& ctx, Id arg_id) {
|
||||
ctx.advance_to(
|
||||
visit_format_arg(arg_formatter<Range>(ctx, &parse_ctx), ctx.arg(arg_id)));
|
||||
}
|
||||
|
||||
// vformat_to is defined in a subnamespace to prevent ADL.
|
||||
namespace cf {
|
||||
template <typename Context, typename Range, typename CompiledFormat>
|
||||
auto vformat_to(Range out, CompiledFormat& cf, basic_format_args<Context> args)
|
||||
-> typename Context::iterator {
|
||||
using char_type = typename Context::char_type;
|
||||
basic_format_parse_context<char_type> parse_ctx(
|
||||
to_string_view(cf.format_str_));
|
||||
Context ctx(out.begin(), args);
|
||||
|
||||
const auto& parts = cf.parts();
|
||||
for (auto part_it = std::begin(parts); part_it != std::end(parts);
|
||||
++part_it) {
|
||||
const auto& part = *part_it;
|
||||
const auto& value = part.val;
|
||||
|
||||
using format_part_t = format_part<char_type>;
|
||||
switch (part.part_kind) {
|
||||
case format_part_t::kind::text: {
|
||||
const auto text = value.str;
|
||||
auto output = ctx.out();
|
||||
auto&& it = reserve(output, text.size());
|
||||
it = std::copy_n(text.begin(), text.size(), it);
|
||||
ctx.advance_to(output);
|
||||
break;
|
||||
}
|
||||
|
||||
case format_part_t::kind::arg_index:
|
||||
advance_to(parse_ctx, part.arg_id_end);
|
||||
internal::format_arg<Range>(parse_ctx, ctx, value.arg_index);
|
||||
break;
|
||||
|
||||
case format_part_t::kind::arg_name:
|
||||
advance_to(parse_ctx, part.arg_id_end);
|
||||
internal::format_arg<Range>(parse_ctx, ctx, value.str);
|
||||
break;
|
||||
|
||||
case format_part_t::kind::replacement: {
|
||||
const auto& arg_id_value = value.repl.arg_id.val;
|
||||
const auto arg = value.repl.arg_id.kind == arg_id_kind::index
|
||||
? ctx.arg(arg_id_value.index)
|
||||
: ctx.arg(arg_id_value.name);
|
||||
|
||||
auto specs = value.repl.specs;
|
||||
|
||||
handle_dynamic_spec<width_checker>(specs.width, specs.width_ref, ctx);
|
||||
handle_dynamic_spec<precision_checker>(specs.precision,
|
||||
specs.precision_ref, ctx);
|
||||
|
||||
error_handler h;
|
||||
numeric_specs_checker<error_handler> checker(h, arg.type());
|
||||
if (specs.align == align::numeric) checker.require_numeric_argument();
|
||||
if (specs.sign != sign::none) checker.check_sign();
|
||||
if (specs.alt) checker.require_numeric_argument();
|
||||
if (specs.precision >= 0) checker.check_precision();
|
||||
|
||||
advance_to(parse_ctx, part.arg_id_end);
|
||||
ctx.advance_to(
|
||||
visit_format_arg(arg_formatter<Range>(ctx, nullptr, &specs), arg));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ctx.out();
|
||||
}
|
||||
} // namespace cf
|
||||
|
||||
struct basic_compiled_format {};
|
||||
|
||||
template <typename S, typename = void>
|
||||
struct compiled_format_base : basic_compiled_format {
|
||||
using char_type = char_t<S>;
|
||||
using parts_container = std::vector<internal::format_part<char_type>>;
|
||||
|
||||
parts_container compiled_parts;
|
||||
|
||||
explicit compiled_format_base(basic_string_view<char_type> format_str) {
|
||||
compile_format_string<false>(format_str,
|
||||
[this](const format_part<char_type>& part) {
|
||||
compiled_parts.push_back(part);
|
||||
});
|
||||
}
|
||||
|
||||
const parts_container& parts() const { return compiled_parts; }
|
||||
};
|
||||
|
||||
template <typename Char, unsigned N> struct format_part_array {
|
||||
format_part<Char> data[N] = {};
|
||||
FMT_CONSTEXPR format_part_array() = default;
|
||||
};
|
||||
|
||||
template <typename Char, unsigned N>
|
||||
FMT_CONSTEXPR format_part_array<Char, N> compile_to_parts(
|
||||
basic_string_view<Char> format_str) {
|
||||
format_part_array<Char, N> parts;
|
||||
unsigned counter = 0;
|
||||
// This is not a lambda for compatibility with older compilers.
|
||||
struct {
|
||||
format_part<Char>* parts;
|
||||
unsigned* counter;
|
||||
FMT_CONSTEXPR void operator()(const format_part<Char>& part) {
|
||||
parts[(*counter)++] = part;
|
||||
}
|
||||
} collector{parts.data, &counter};
|
||||
compile_format_string<true>(format_str, collector);
|
||||
if (counter < N) {
|
||||
parts.data[counter] =
|
||||
format_part<Char>::make_text(basic_string_view<Char>());
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
template <typename T> constexpr const T& constexpr_max(const T& a, const T& b) {
|
||||
return (a < b) ? b : a;
|
||||
}
|
||||
|
||||
template <typename S>
|
||||
struct compiled_format_base<S, enable_if_t<is_compile_string<S>::value>>
|
||||
: basic_compiled_format {
|
||||
using char_type = char_t<S>;
|
||||
|
||||
FMT_CONSTEXPR explicit compiled_format_base(basic_string_view<char_type>) {}
|
||||
|
||||
// Workaround for old compilers. Format string compilation will not be
|
||||
// performed there anyway.
|
||||
#if FMT_USE_CONSTEXPR
|
||||
static FMT_CONSTEXPR_DECL const unsigned number_of_format_parts =
|
||||
compiletime_prepared_parts_type_provider::count_parts();
|
||||
static FMT_CONSTEXPR_DECL const unsigned num_format_parts =
|
||||
constexpr_max(count_parts(to_string_view(S())), 1u);
|
||||
#else
|
||||
static const unsigned number_of_format_parts = 0u;
|
||||
static const unsigned num_format_parts = 1;
|
||||
#endif
|
||||
|
||||
public:
|
||||
template <unsigned N> struct format_parts_array {
|
||||
using value_type = format_part<char_type>;
|
||||
using parts_container = format_part<char_type>[num_format_parts];
|
||||
|
||||
FMT_CONSTEXPR format_parts_array() : arr{} {}
|
||||
|
||||
FMT_CONSTEXPR value_type& operator[](unsigned ind) { return arr[ind]; }
|
||||
|
||||
FMT_CONSTEXPR const value_type* begin() const { return arr; }
|
||||
FMT_CONSTEXPR const value_type* end() const { return begin() + N; }
|
||||
|
||||
private:
|
||||
value_type arr[N];
|
||||
};
|
||||
|
||||
struct empty {
|
||||
// Parts preparator will search for it
|
||||
using value_type = format_part<char_type>;
|
||||
};
|
||||
|
||||
using type = conditional_t<number_of_format_parts != 0,
|
||||
format_parts_array<number_of_format_parts>, empty>;
|
||||
};
|
||||
|
||||
template <typename Parts> class compiletime_prepared_parts_collector {
|
||||
private:
|
||||
using format_part = typename Parts::value_type;
|
||||
|
||||
public:
|
||||
FMT_CONSTEXPR explicit compiletime_prepared_parts_collector(Parts& parts)
|
||||
: parts_{parts}, counter_{0u} {}
|
||||
|
||||
FMT_CONSTEXPR void push_back(format_part part) { parts_[counter_++] = part; }
|
||||
|
||||
FMT_CONSTEXPR format_part& back() { return parts_[counter_ - 1]; }
|
||||
|
||||
private:
|
||||
Parts& parts_;
|
||||
unsigned counter_;
|
||||
};
|
||||
|
||||
template <typename PartsContainer, typename Char>
|
||||
FMT_CONSTEXPR PartsContainer prepare_parts(basic_string_view<Char> format) {
|
||||
PartsContainer parts;
|
||||
internal::parse_format_string</*IS_CONSTEXPR=*/false>(
|
||||
format, format_preparation_handler<Char, PartsContainer>(format, parts));
|
||||
return parts;
|
||||
}
|
||||
|
||||
template <typename PartsContainer, typename Char>
|
||||
FMT_CONSTEXPR PartsContainer
|
||||
prepare_compiletime_parts(basic_string_view<Char> format) {
|
||||
using collector = compiletime_prepared_parts_collector<PartsContainer>;
|
||||
|
||||
PartsContainer parts;
|
||||
collector c(parts);
|
||||
internal::parse_format_string</*IS_CONSTEXPR=*/true>(
|
||||
format, format_preparation_handler<Char, collector>(format, c));
|
||||
return parts;
|
||||
}
|
||||
|
||||
template <typename PartsContainer> class runtime_parts_provider {
|
||||
public:
|
||||
runtime_parts_provider() = delete;
|
||||
template <typename Char>
|
||||
runtime_parts_provider(basic_string_view<Char> format)
|
||||
: parts_(prepare_parts<PartsContainer>(format)) {}
|
||||
|
||||
const PartsContainer& parts() const { return parts_; }
|
||||
|
||||
private:
|
||||
PartsContainer parts_;
|
||||
};
|
||||
|
||||
template <typename Format, typename PartsContainer>
|
||||
struct compiletime_parts_provider {
|
||||
compiletime_parts_provider() = delete;
|
||||
template <typename Char>
|
||||
FMT_CONSTEXPR compiletime_parts_provider(basic_string_view<Char>) {}
|
||||
|
||||
const PartsContainer& parts() const {
|
||||
static FMT_CONSTEXPR_DECL const PartsContainer prepared_parts =
|
||||
prepare_compiletime_parts<PartsContainer>(
|
||||
internal::to_string_view(Format{}));
|
||||
|
||||
return prepared_parts;
|
||||
const parts_container& parts() const {
|
||||
static FMT_CONSTEXPR_DECL const auto compiled_parts =
|
||||
compile_to_parts<char_type, num_format_parts>(
|
||||
internal::to_string_view(S()));
|
||||
return compiled_parts.data;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename S, typename... Args>
|
||||
class compiled_format : private compiled_format_base<S> {
|
||||
public:
|
||||
using typename compiled_format_base<S>::char_type;
|
||||
|
||||
private:
|
||||
basic_string_view<char_type> format_str_;
|
||||
|
||||
template <typename Context, typename Range, typename CompiledFormat>
|
||||
friend auto cf::vformat_to(Range out, CompiledFormat& cf,
|
||||
basic_format_args<Context> args) ->
|
||||
typename Context::iterator;
|
||||
|
||||
public:
|
||||
compiled_format() = delete;
|
||||
explicit constexpr compiled_format(basic_string_view<char_type> format_str)
|
||||
: compiled_format_base<S>(format_str), format_str_(format_str) {}
|
||||
};
|
||||
|
||||
#ifdef __cpp_if_constexpr
|
||||
template <typename... Args> struct type_list {};
|
||||
|
||||
// Returns a reference to the argument at index N from [first, rest...].
|
||||
template <int N, typename T, typename... Args>
|
||||
constexpr const auto& get(const T& first, const Args&... rest) {
|
||||
static_assert(N < 1 + sizeof...(Args), "index is out of bounds");
|
||||
if constexpr (N == 0)
|
||||
return first;
|
||||
else
|
||||
return get<N - 1>(rest...);
|
||||
}
|
||||
|
||||
template <int N, typename> struct get_type_impl;
|
||||
|
||||
template <int N, typename... Args> struct get_type_impl<N, type_list<Args...>> {
|
||||
using type = remove_cvref_t<decltype(get<N>(std::declval<Args>()...))>;
|
||||
};
|
||||
|
||||
template <int N, typename T>
|
||||
using get_type = typename get_type_impl<N, T>::type;
|
||||
|
||||
template <typename T> struct is_compiled_format : std::false_type {};
|
||||
|
||||
template <typename Char> struct text {
|
||||
basic_string_view<Char> data;
|
||||
using char_type = Char;
|
||||
|
||||
template <typename OutputIt, typename... Args>
|
||||
OutputIt format(OutputIt out, const Args&...) const {
|
||||
// TODO: reserve
|
||||
return copy_str<Char>(data.begin(), data.end(), out);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Char>
|
||||
struct is_compiled_format<text<Char>> : std::true_type {};
|
||||
|
||||
template <typename Char>
|
||||
constexpr text<Char> make_text(basic_string_view<Char> s, size_t pos,
|
||||
size_t size) {
|
||||
return {{&s[pos], size}};
|
||||
}
|
||||
|
||||
template <typename Char, typename OutputIt, typename T,
|
||||
std::enable_if_t<std::is_integral_v<T>, int> = 0>
|
||||
OutputIt format_default(OutputIt out, T value) {
|
||||
// TODO: reserve
|
||||
format_int fi(value);
|
||||
return std::copy(fi.data(), fi.data() + fi.size(), out);
|
||||
}
|
||||
|
||||
template <typename Char, typename OutputIt>
|
||||
OutputIt format_default(OutputIt out, double value) {
|
||||
writer w(out);
|
||||
w.write(value);
|
||||
return w.out();
|
||||
}
|
||||
|
||||
template <typename Char, typename OutputIt>
|
||||
OutputIt format_default(OutputIt out, Char value) {
|
||||
*out++ = value;
|
||||
return out;
|
||||
}
|
||||
|
||||
template <typename Char, typename OutputIt>
|
||||
OutputIt format_default(OutputIt out, const Char* value) {
|
||||
auto length = std::char_traits<Char>::length(value);
|
||||
return copy_str<Char>(value, value + length, out);
|
||||
}
|
||||
|
||||
// A replacement field that refers to argument N.
|
||||
template <typename Char, typename T, int N> struct field {
|
||||
using char_type = Char;
|
||||
|
||||
template <typename OutputIt, typename... Args>
|
||||
OutputIt format(OutputIt out, const Args&... args) const {
|
||||
// This ensures that the argument type is convertile to `const T&`.
|
||||
const T& arg = get<N>(args...);
|
||||
return format_default<Char>(out, arg);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Char, typename T, int N>
|
||||
struct is_compiled_format<field<Char, T, N>> : std::true_type {};
|
||||
|
||||
template <typename L, typename R> struct concat {
|
||||
L lhs;
|
||||
R rhs;
|
||||
using char_type = typename L::char_type;
|
||||
|
||||
template <typename OutputIt, typename... Args>
|
||||
OutputIt format(OutputIt out, const Args&... args) const {
|
||||
out = lhs.format(out, args...);
|
||||
return rhs.format(out, args...);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename L, typename R>
|
||||
struct is_compiled_format<concat<L, R>> : std::true_type {};
|
||||
|
||||
template <typename L, typename R>
|
||||
constexpr concat<L, R> make_concat(L lhs, R rhs) {
|
||||
return {lhs, rhs};
|
||||
}
|
||||
|
||||
struct unknown_format {};
|
||||
|
||||
template <typename Char>
|
||||
constexpr size_t parse_text(basic_string_view<Char> str, size_t pos) {
|
||||
for (size_t size = str.size(); pos != size; ++pos) {
|
||||
if (str[pos] == '{' || str[pos] == '}') break;
|
||||
}
|
||||
return pos;
|
||||
}
|
||||
|
||||
template <typename Args, size_t POS, int ID, typename S>
|
||||
constexpr auto compile_format_string(S format_str);
|
||||
|
||||
template <typename Args, size_t POS, int ID, typename T, typename S>
|
||||
constexpr auto parse_tail(T head, S format_str) {
|
||||
if constexpr (POS != to_string_view(format_str).size()) {
|
||||
constexpr auto tail = compile_format_string<Args, POS, ID>(format_str);
|
||||
if constexpr (std::is_same<remove_cvref_t<decltype(tail)>,
|
||||
unknown_format>())
|
||||
return tail;
|
||||
else
|
||||
return make_concat(head, tail);
|
||||
} else {
|
||||
return head;
|
||||
}
|
||||
}
|
||||
|
||||
// Compiles a non-empty format string and returns the compiled representation
|
||||
// or unknown_format() on unrecognized input.
|
||||
template <typename Args, size_t POS, int ID, typename S>
|
||||
constexpr auto compile_format_string(S format_str) {
|
||||
using char_type = typename S::char_type;
|
||||
constexpr basic_string_view<char_type> str = format_str;
|
||||
if constexpr (str[POS] == '{') {
|
||||
if (POS + 1 == str.size())
|
||||
throw format_error("unmatched '{' in format string");
|
||||
if constexpr (str[POS + 1] == '{') {
|
||||
return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), format_str);
|
||||
} else if constexpr (str[POS + 1] == '}') {
|
||||
using type = get_type<ID, Args>;
|
||||
if constexpr (std::is_same<type, int>::value) {
|
||||
return parse_tail<Args, POS + 2, ID + 1>(field<char_type, type, ID>(),
|
||||
format_str);
|
||||
} else {
|
||||
return unknown_format();
|
||||
}
|
||||
} else {
|
||||
return unknown_format();
|
||||
}
|
||||
} else if constexpr (str[POS] == '}') {
|
||||
if (POS + 1 == str.size())
|
||||
throw format_error("unmatched '}' in format string");
|
||||
return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), format_str);
|
||||
} else {
|
||||
constexpr auto end = parse_text(str, POS + 1);
|
||||
return parse_tail<Args, end, ID>(make_text(str, POS, end - POS),
|
||||
format_str);
|
||||
}
|
||||
}
|
||||
#endif // __cpp_if_constexpr
|
||||
} // namespace internal
|
||||
|
||||
#if FMT_USE_CONSTEXPR
|
||||
# ifdef __cpp_if_constexpr
|
||||
template <typename... Args, typename S,
|
||||
FMT_ENABLE_IF(is_compile_string<S>::value)>
|
||||
FMT_CONSTEXPR auto compile(S format_str) -> internal::prepared_format<
|
||||
S,
|
||||
internal::compiletime_parts_provider<
|
||||
S,
|
||||
typename internal::compiletime_prepared_parts_type_provider<S>::type>,
|
||||
Args...> {
|
||||
return format_str;
|
||||
}
|
||||
#endif
|
||||
|
||||
template <typename... Args, typename Char, size_t N>
|
||||
auto compile(const Char (&format_str)[N]) -> internal::prepared_format<
|
||||
std::basic_string<Char>,
|
||||
internal::runtime_parts_provider<std::vector<internal::format_part<Char>>>,
|
||||
Args...> {
|
||||
return std::basic_string<Char>(format_str, N - 1);
|
||||
constexpr auto compile(S format_str) {
|
||||
constexpr basic_string_view<typename S::char_type> str = format_str;
|
||||
if constexpr (str.size() == 0) {
|
||||
return internal::make_text(str, 0, 0);
|
||||
} else {
|
||||
constexpr auto result =
|
||||
internal::compile_format_string<internal::type_list<Args...>, 0, 0>(
|
||||
format_str);
|
||||
if constexpr (std::is_same<remove_cvref_t<decltype(result)>,
|
||||
internal::unknown_format>()) {
|
||||
return internal::compiled_format<S, Args...>(to_string_view(format_str));
|
||||
} else {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename CompiledFormat, typename... Args,
|
||||
typename Char = typename CompiledFormat::char_type>
|
||||
typename Char = typename CompiledFormat::char_type,
|
||||
FMT_ENABLE_IF(internal::is_compiled_format<CompiledFormat>::value)>
|
||||
std::basic_string<Char> format(const CompiledFormat& cf, const Args&... args) {
|
||||
basic_memory_buffer<Char> buffer;
|
||||
using range = internal::buffer_range<Char>;
|
||||
using context = buffer_context<Char>;
|
||||
cf.template vformat_to<range, context>(range(buffer),
|
||||
{make_format_args<context>(args...)});
|
||||
cf.format(std::back_inserter(buffer), args...);
|
||||
return to_string(buffer);
|
||||
}
|
||||
|
||||
template <typename OutputIt, typename CompiledFormat, typename... Args>
|
||||
template <typename OutputIt, typename CompiledFormat, typename... Args,
|
||||
FMT_ENABLE_IF(internal::is_compiled_format<CompiledFormat>::value)>
|
||||
OutputIt format_to(OutputIt out, const CompiledFormat& cf,
|
||||
const Args&... args) {
|
||||
return cf.format(out, args...);
|
||||
}
|
||||
# else
|
||||
template <typename... Args, typename S,
|
||||
FMT_ENABLE_IF(is_compile_string<S>::value)>
|
||||
constexpr auto compile(S format_str) -> internal::compiled_format<S, Args...> {
|
||||
return internal::compiled_format<S, Args...>(to_string_view(format_str));
|
||||
}
|
||||
# endif // __cpp_if_constexpr
|
||||
#endif // FMT_USE_CONSTEXPR
|
||||
|
||||
// Compiles the format string which must be a string literal.
|
||||
template <typename... Args, typename Char, size_t N>
|
||||
auto compile(const Char (&format_str)[N])
|
||||
-> internal::compiled_format<const Char*, Args...> {
|
||||
return internal::compiled_format<const Char*, Args...>(
|
||||
basic_string_view<Char>(format_str, N - 1));
|
||||
}
|
||||
|
||||
template <typename CompiledFormat, typename... Args,
|
||||
typename Char = typename CompiledFormat::char_type,
|
||||
FMT_ENABLE_IF(std::is_base_of<internal::basic_compiled_format,
|
||||
CompiledFormat>::value)>
|
||||
std::basic_string<Char> format(const CompiledFormat& cf, const Args&... args) {
|
||||
basic_memory_buffer<Char> buffer;
|
||||
using range = buffer_range<Char>;
|
||||
using context = buffer_context<Char>;
|
||||
internal::cf::vformat_to<context>(range(buffer), cf,
|
||||
make_format_args<context>(args...));
|
||||
return to_string(buffer);
|
||||
}
|
||||
|
||||
template <typename OutputIt, typename CompiledFormat, typename... Args,
|
||||
FMT_ENABLE_IF(std::is_base_of<internal::basic_compiled_format,
|
||||
CompiledFormat>::value)>
|
||||
OutputIt format_to(OutputIt out, const CompiledFormat& cf,
|
||||
const Args&... args) {
|
||||
using char_type = typename CompiledFormat::char_type;
|
||||
using range = internal::output_range<OutputIt, char_type>;
|
||||
using context = format_context_t<OutputIt, char_type>;
|
||||
return cf.template vformat_to<range, context>(
|
||||
range(out), {make_format_args<context>(args...)});
|
||||
return internal::cf::vformat_to<context>(range(out), cf,
|
||||
make_format_args<context>(args...));
|
||||
}
|
||||
|
||||
template <typename OutputIt, typename CompiledFormat, typename... Args,
|
||||
@@ -455,10 +587,7 @@ format_to_n_result<OutputIt> format_to_n(OutputIt out, size_t n,
|
||||
|
||||
template <typename CompiledFormat, typename... Args>
|
||||
std::size_t formatted_size(const CompiledFormat& cf, const Args&... args) {
|
||||
return fmt::format_to(
|
||||
internal::counting_iterator<typename CompiledFormat::char_type>(),
|
||||
cf, args...)
|
||||
.count();
|
||||
return format_to(internal::counting_iterator(), cf, args...).count();
|
||||
}
|
||||
|
||||
FMT_END_NAMESPACE
|
||||
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -9,6 +9,7 @@
|
||||
#define FMT_LOCALE_H_
|
||||
|
||||
#include <locale>
|
||||
|
||||
#include "format.h"
|
||||
|
||||
FMT_BEGIN_NAMESPACE
|
||||
@@ -18,16 +19,16 @@ template <typename Char>
|
||||
typename buffer_context<Char>::iterator vformat_to(
|
||||
const std::locale& loc, buffer<Char>& buf,
|
||||
basic_string_view<Char> format_str,
|
||||
basic_format_args<buffer_context<Char>> args) {
|
||||
basic_format_args<buffer_context<type_identity_t<Char>>> args) {
|
||||
using range = buffer_range<Char>;
|
||||
return vformat_to<arg_formatter<range>>(buf, to_string_view(format_str), args,
|
||||
internal::locale_ref(loc));
|
||||
}
|
||||
|
||||
template <typename Char>
|
||||
std::basic_string<Char> vformat(const std::locale& loc,
|
||||
basic_string_view<Char> format_str,
|
||||
basic_format_args<buffer_context<Char>> args) {
|
||||
std::basic_string<Char> vformat(
|
||||
const std::locale& loc, basic_string_view<Char> format_str,
|
||||
basic_format_args<buffer_context<type_identity_t<Char>>> args) {
|
||||
basic_memory_buffer<Char> buffer;
|
||||
internal::vformat_to(loc, buffer, format_str, args);
|
||||
return fmt::to_string(buffer);
|
||||
@@ -37,7 +38,7 @@ std::basic_string<Char> vformat(const std::locale& loc,
|
||||
template <typename S, typename Char = char_t<S>>
|
||||
inline std::basic_string<Char> vformat(
|
||||
const std::locale& loc, const S& format_str,
|
||||
basic_format_args<buffer_context<Char>> args) {
|
||||
basic_format_args<buffer_context<type_identity_t<Char>>> args) {
|
||||
return internal::vformat(loc, to_string_view(format_str), args);
|
||||
}
|
||||
|
||||
@@ -46,15 +47,15 @@ inline std::basic_string<Char> format(const std::locale& loc,
|
||||
const S& format_str, Args&&... args) {
|
||||
return internal::vformat(
|
||||
loc, to_string_view(format_str),
|
||||
{internal::make_args_checked<Args...>(format_str, args...)});
|
||||
internal::make_args_checked<Args...>(format_str, args...));
|
||||
}
|
||||
|
||||
template <typename S, typename OutputIt, typename... Args,
|
||||
typename Char = enable_if_t<
|
||||
internal::is_output_iterator<OutputIt>::value, char_t<S>>>
|
||||
inline OutputIt vformat_to(OutputIt out, const std::locale& loc,
|
||||
const S& format_str,
|
||||
format_args_t<OutputIt, Char> args) {
|
||||
inline OutputIt vformat_to(
|
||||
OutputIt out, const std::locale& loc, const S& format_str,
|
||||
format_args_t<type_identity_t<OutputIt>, Char> args) {
|
||||
using range = internal::output_range<OutputIt, Char>;
|
||||
return vformat_to<arg_formatter<range>>(
|
||||
range(out), to_string_view(format_str), args, internal::locale_ref(loc));
|
||||
|
@@ -9,9 +9,14 @@
|
||||
#define FMT_OSTREAM_H_
|
||||
|
||||
#include <ostream>
|
||||
|
||||
#include "format.h"
|
||||
|
||||
FMT_BEGIN_NAMESPACE
|
||||
|
||||
template <typename CHar> class basic_printf_parse_context;
|
||||
template <typename OutputIt, typename Char> class basic_printf_context;
|
||||
|
||||
namespace internal {
|
||||
|
||||
template <class Char> class formatbuf : public std::basic_streambuf<Char> {
|
||||
@@ -46,9 +51,13 @@ template <class Char> class formatbuf : public std::basic_streambuf<Char> {
|
||||
|
||||
template <typename Char> struct test_stream : std::basic_ostream<Char> {
|
||||
private:
|
||||
struct null;
|
||||
// Hide all operator<< from std::basic_ostream<Char>.
|
||||
void operator<<(null);
|
||||
void_t<> operator<<(null<>);
|
||||
void_t<> operator<<(const Char*);
|
||||
|
||||
template <typename T, FMT_ENABLE_IF(std::is_convertible<T, int>::value &&
|
||||
!std::is_enum<T>::value)>
|
||||
void_t<> operator<<(T);
|
||||
};
|
||||
|
||||
// Checks if T has a user-defined operator<< (e.g. not a member of
|
||||
@@ -56,9 +65,9 @@ template <typename Char> struct test_stream : std::basic_ostream<Char> {
|
||||
template <typename T, typename Char> class is_streamable {
|
||||
private:
|
||||
template <typename U>
|
||||
static decltype((void)(std::declval<test_stream<Char>&>()
|
||||
<< std::declval<U>()),
|
||||
std::true_type())
|
||||
static bool_constant<!std::is_same<decltype(std::declval<test_stream<Char>&>()
|
||||
<< std::declval<U>()),
|
||||
void_t<>>::value>
|
||||
test(int);
|
||||
|
||||
template <typename> static std::false_type test(...);
|
||||
@@ -75,8 +84,7 @@ void write(std::basic_ostream<Char>& os, buffer<Char>& buf) {
|
||||
const Char* buf_data = buf.data();
|
||||
using unsigned_streamsize = std::make_unsigned<std::streamsize>::type;
|
||||
unsigned_streamsize size = buf.size();
|
||||
unsigned_streamsize max_size =
|
||||
to_unsigned((std::numeric_limits<std::streamsize>::max)());
|
||||
unsigned_streamsize max_size = to_unsigned(max_value<std::streamsize>());
|
||||
do {
|
||||
unsigned_streamsize n = size <= max_size ? size : max_size;
|
||||
os.write(buf_data, static_cast<std::streamsize>(n));
|
||||
@@ -86,9 +94,13 @@ void write(std::basic_ostream<Char>& os, buffer<Char>& buf) {
|
||||
}
|
||||
|
||||
template <typename Char, typename T>
|
||||
void format_value(buffer<Char>& buf, const T& value) {
|
||||
void format_value(buffer<Char>& buf, const T& value,
|
||||
locale_ref loc = locale_ref()) {
|
||||
formatbuf<Char> format_buf(buf);
|
||||
std::basic_ostream<Char> output(&format_buf);
|
||||
#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR)
|
||||
if (loc) output.imbue(loc.get<std::locale>());
|
||||
#endif
|
||||
output.exceptions(std::ios_base::failbit | std::ios_base::badbit);
|
||||
output << value;
|
||||
buf.resize(buf.size());
|
||||
@@ -97,20 +109,38 @@ void format_value(buffer<Char>& buf, const T& value) {
|
||||
// Formats an object of type T that has an overloaded ostream operator<<.
|
||||
template <typename T, typename Char>
|
||||
struct fallback_formatter<T, Char, enable_if_t<is_streamable<T, Char>::value>>
|
||||
: formatter<basic_string_view<Char>, Char> {
|
||||
template <typename Context>
|
||||
auto format(const T& value, Context& ctx) -> decltype(ctx.out()) {
|
||||
: private formatter<basic_string_view<Char>, Char> {
|
||||
auto parse(basic_format_parse_context<Char>& ctx) -> decltype(ctx.begin()) {
|
||||
return formatter<basic_string_view<Char>, Char>::parse(ctx);
|
||||
}
|
||||
template <typename ParseCtx,
|
||||
FMT_ENABLE_IF(std::is_same<
|
||||
ParseCtx, basic_printf_parse_context<Char>>::value)>
|
||||
auto parse(ParseCtx& ctx) -> decltype(ctx.begin()) {
|
||||
return ctx.begin();
|
||||
}
|
||||
|
||||
template <typename OutputIt>
|
||||
auto format(const T& value, basic_format_context<OutputIt, Char>& ctx)
|
||||
-> OutputIt {
|
||||
basic_memory_buffer<Char> buffer;
|
||||
format_value(buffer, value);
|
||||
format_value(buffer, value, ctx.locale());
|
||||
basic_string_view<Char> str(buffer.data(), buffer.size());
|
||||
return formatter<basic_string_view<Char>, Char>::format(str, ctx);
|
||||
}
|
||||
template <typename OutputIt>
|
||||
auto format(const T& value, basic_printf_context<OutputIt, Char>& ctx)
|
||||
-> OutputIt {
|
||||
basic_memory_buffer<Char> buffer;
|
||||
format_value(buffer, value, ctx.locale());
|
||||
return std::copy(buffer.begin(), buffer.end(), ctx.out());
|
||||
}
|
||||
};
|
||||
} // namespace internal
|
||||
|
||||
template <typename Char>
|
||||
void vprint(std::basic_ostream<Char>& os, basic_string_view<Char> format_str,
|
||||
basic_format_args<buffer_context<Char>> args) {
|
||||
basic_format_args<buffer_context<type_identity_t<Char>>> args) {
|
||||
basic_memory_buffer<Char> buffer;
|
||||
internal::vformat_to(buffer, format_str, args);
|
||||
internal::write(os, buffer);
|
||||
@@ -129,7 +159,7 @@ template <typename S, typename... Args,
|
||||
typename Char = enable_if_t<internal::is_string<S>::value, char_t<S>>>
|
||||
void print(std::basic_ostream<Char>& os, const S& format_str, Args&&... args) {
|
||||
vprint(os, to_string_view(format_str),
|
||||
{internal::make_args_checked<Args...>(format_str, args...)});
|
||||
internal::make_args_checked<Args...>(format_str, args...));
|
||||
}
|
||||
FMT_END_NAMESPACE
|
||||
|
||||
|
@@ -1,311 +1,2 @@
|
||||
// A C++ interface to POSIX functions.
|
||||
//
|
||||
// Copyright (c) 2012 - 2016, Victor Zverovich
|
||||
// All rights reserved.
|
||||
//
|
||||
// For the license information refer to format.h.
|
||||
|
||||
#ifndef FMT_POSIX_H_
|
||||
#define FMT_POSIX_H_
|
||||
|
||||
#if defined(__MINGW32__) || defined(__CYGWIN__)
|
||||
// Workaround MinGW bug https://sourceforge.net/p/mingw/bugs/2024/.
|
||||
# undef __STRICT_ANSI__
|
||||
#endif
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h> // for O_RDONLY
|
||||
#include <locale.h> // for locale_t
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h> // for strtod_l
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
#if defined __APPLE__ || defined(__FreeBSD__)
|
||||
# include <xlocale.h> // for LC_NUMERIC_MASK on OS X
|
||||
#endif
|
||||
|
||||
#include "format.h"
|
||||
|
||||
#ifndef FMT_POSIX
|
||||
# if defined(_WIN32) && !defined(__MINGW32__)
|
||||
// Fix warnings about deprecated symbols.
|
||||
# define FMT_POSIX(call) _##call
|
||||
# else
|
||||
# define FMT_POSIX(call) call
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// Calls to system functions are wrapped in FMT_SYSTEM for testability.
|
||||
#ifdef FMT_SYSTEM
|
||||
# define FMT_POSIX_CALL(call) FMT_SYSTEM(call)
|
||||
#else
|
||||
# define FMT_SYSTEM(call) call
|
||||
# ifdef _WIN32
|
||||
// Fix warnings about deprecated symbols.
|
||||
# define FMT_POSIX_CALL(call) ::_##call
|
||||
# else
|
||||
# define FMT_POSIX_CALL(call) ::call
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// Retries the expression while it evaluates to error_result and errno
|
||||
// equals to EINTR.
|
||||
#ifndef _WIN32
|
||||
# define FMT_RETRY_VAL(result, expression, error_result) \
|
||||
do { \
|
||||
result = (expression); \
|
||||
} while (result == error_result && errno == EINTR)
|
||||
#else
|
||||
# define FMT_RETRY_VAL(result, expression, error_result) result = (expression)
|
||||
#endif
|
||||
|
||||
#define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1)
|
||||
|
||||
FMT_BEGIN_NAMESPACE
|
||||
|
||||
/**
|
||||
\rst
|
||||
A reference to a null-terminated string. It can be constructed from a C
|
||||
string or ``std::string``.
|
||||
|
||||
You can use one of the following type aliases for common character types:
|
||||
|
||||
+---------------+-----------------------------+
|
||||
| Type | Definition |
|
||||
+===============+=============================+
|
||||
| cstring_view | basic_cstring_view<char> |
|
||||
+---------------+-----------------------------+
|
||||
| wcstring_view | basic_cstring_view<wchar_t> |
|
||||
+---------------+-----------------------------+
|
||||
|
||||
This class is most useful as a parameter type to allow passing
|
||||
different types of strings to a function, for example::
|
||||
|
||||
template <typename... Args>
|
||||
std::string format(cstring_view format_str, const Args & ... args);
|
||||
|
||||
format("{}", 42);
|
||||
format(std::string("{}"), 42);
|
||||
\endrst
|
||||
*/
|
||||
template <typename Char> class basic_cstring_view {
|
||||
private:
|
||||
const Char* data_;
|
||||
|
||||
public:
|
||||
/** Constructs a string reference object from a C string. */
|
||||
basic_cstring_view(const Char* s) : data_(s) {}
|
||||
|
||||
/**
|
||||
\rst
|
||||
Constructs a string reference from an ``std::string`` object.
|
||||
\endrst
|
||||
*/
|
||||
basic_cstring_view(const std::basic_string<Char>& s) : data_(s.c_str()) {}
|
||||
|
||||
/** Returns the pointer to a C string. */
|
||||
const Char* c_str() const { return data_; }
|
||||
};
|
||||
|
||||
using cstring_view = basic_cstring_view<char>;
|
||||
using wcstring_view = basic_cstring_view<wchar_t>;
|
||||
|
||||
// An error code.
|
||||
class error_code {
|
||||
private:
|
||||
int value_;
|
||||
|
||||
public:
|
||||
explicit error_code(int value = 0) FMT_NOEXCEPT : value_(value) {}
|
||||
|
||||
int get() const FMT_NOEXCEPT { return value_; }
|
||||
};
|
||||
|
||||
// A buffered file.
|
||||
class buffered_file {
|
||||
private:
|
||||
FILE* file_;
|
||||
|
||||
friend class file;
|
||||
|
||||
explicit buffered_file(FILE* f) : file_(f) {}
|
||||
|
||||
public:
|
||||
// Constructs a buffered_file object which doesn't represent any file.
|
||||
buffered_file() FMT_NOEXCEPT : file_(nullptr) {}
|
||||
|
||||
// Destroys the object closing the file it represents if any.
|
||||
FMT_API ~buffered_file() FMT_NOEXCEPT;
|
||||
|
||||
private:
|
||||
buffered_file(const buffered_file&) = delete;
|
||||
void operator=(const buffered_file&) = delete;
|
||||
|
||||
public:
|
||||
buffered_file(buffered_file&& other) FMT_NOEXCEPT : file_(other.file_) {
|
||||
other.file_ = nullptr;
|
||||
}
|
||||
|
||||
buffered_file& operator=(buffered_file&& other) {
|
||||
close();
|
||||
file_ = other.file_;
|
||||
other.file_ = nullptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Opens a file.
|
||||
FMT_API buffered_file(cstring_view filename, cstring_view mode);
|
||||
|
||||
// Closes the file.
|
||||
FMT_API void close();
|
||||
|
||||
// Returns the pointer to a FILE object representing this file.
|
||||
FILE* get() const FMT_NOEXCEPT { return file_; }
|
||||
|
||||
// We place parentheses around fileno to workaround a bug in some versions
|
||||
// of MinGW that define fileno as a macro.
|
||||
FMT_API int(fileno)() const;
|
||||
|
||||
void vprint(string_view format_str, format_args args) {
|
||||
fmt::vprint(file_, format_str, args);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
inline void print(string_view format_str, const Args&... args) {
|
||||
vprint(format_str, make_format_args(args...));
|
||||
}
|
||||
};
|
||||
|
||||
// A file. Closed file is represented by a file object with descriptor -1.
|
||||
// Methods that are not declared with FMT_NOEXCEPT may throw
|
||||
// fmt::system_error in case of failure. Note that some errors such as
|
||||
// closing the file multiple times will cause a crash on Windows rather
|
||||
// than an exception. You can get standard behavior by overriding the
|
||||
// invalid parameter handler with _set_invalid_parameter_handler.
|
||||
class file {
|
||||
private:
|
||||
int fd_; // File descriptor.
|
||||
|
||||
// Constructs a file object with a given descriptor.
|
||||
explicit file(int fd) : fd_(fd) {}
|
||||
|
||||
public:
|
||||
// Possible values for the oflag argument to the constructor.
|
||||
enum {
|
||||
RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only.
|
||||
WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only.
|
||||
RDWR = FMT_POSIX(O_RDWR) // Open for reading and writing.
|
||||
};
|
||||
|
||||
// Constructs a file object which doesn't represent any file.
|
||||
file() FMT_NOEXCEPT : fd_(-1) {}
|
||||
|
||||
// Opens a file and constructs a file object representing this file.
|
||||
FMT_API file(cstring_view path, int oflag);
|
||||
|
||||
private:
|
||||
file(const file&) = delete;
|
||||
void operator=(const file&) = delete;
|
||||
|
||||
public:
|
||||
file(file&& other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; }
|
||||
|
||||
file& operator=(file&& other) {
|
||||
close();
|
||||
fd_ = other.fd_;
|
||||
other.fd_ = -1;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Destroys the object closing the file it represents if any.
|
||||
FMT_API ~file() FMT_NOEXCEPT;
|
||||
|
||||
// Returns the file descriptor.
|
||||
int descriptor() const FMT_NOEXCEPT { return fd_; }
|
||||
|
||||
// Closes the file.
|
||||
FMT_API void close();
|
||||
|
||||
// Returns the file size. The size has signed type for consistency with
|
||||
// stat::st_size.
|
||||
FMT_API long long size() const;
|
||||
|
||||
// Attempts to read count bytes from the file into the specified buffer.
|
||||
FMT_API std::size_t read(void* buffer, std::size_t count);
|
||||
|
||||
// Attempts to write count bytes from the specified buffer to the file.
|
||||
FMT_API std::size_t write(const void* buffer, std::size_t count);
|
||||
|
||||
// Duplicates a file descriptor with the dup function and returns
|
||||
// the duplicate as a file object.
|
||||
FMT_API static file dup(int fd);
|
||||
|
||||
// Makes fd be the copy of this file descriptor, closing fd first if
|
||||
// necessary.
|
||||
FMT_API void dup2(int fd);
|
||||
|
||||
// Makes fd be the copy of this file descriptor, closing fd first if
|
||||
// necessary.
|
||||
FMT_API void dup2(int fd, error_code& ec) FMT_NOEXCEPT;
|
||||
|
||||
// Creates a pipe setting up read_end and write_end file objects for reading
|
||||
// and writing respectively.
|
||||
FMT_API static void pipe(file& read_end, file& write_end);
|
||||
|
||||
// Creates a buffered_file object associated with this file and detaches
|
||||
// this file object from the file.
|
||||
FMT_API buffered_file fdopen(const char* mode);
|
||||
};
|
||||
|
||||
// Returns the memory page size.
|
||||
long getpagesize();
|
||||
|
||||
#ifdef FMT_LOCALE
|
||||
// A "C" numeric locale.
|
||||
class Locale {
|
||||
private:
|
||||
# ifdef _WIN32
|
||||
using locale_t = _locale_t;
|
||||
|
||||
enum { LC_NUMERIC_MASK = LC_NUMERIC };
|
||||
|
||||
static locale_t newlocale(int category_mask, const char* locale, locale_t) {
|
||||
return _create_locale(category_mask, locale);
|
||||
}
|
||||
|
||||
static void freelocale(locale_t locale) { _free_locale(locale); }
|
||||
|
||||
static double strtod_l(const char* nptr, char** endptr, _locale_t locale) {
|
||||
return _strtod_l(nptr, endptr, locale);
|
||||
}
|
||||
# endif
|
||||
|
||||
locale_t locale_;
|
||||
|
||||
Locale(const Locale&) = delete;
|
||||
void operator=(const Locale&) = delete;
|
||||
|
||||
public:
|
||||
using type = locale_t;
|
||||
|
||||
Locale() : locale_(newlocale(LC_NUMERIC_MASK, "C", nullptr)) {
|
||||
if (!locale_) FMT_THROW(system_error(errno, "cannot create locale"));
|
||||
}
|
||||
~Locale() { freelocale(locale_); }
|
||||
|
||||
type get() const { return locale_; }
|
||||
|
||||
// Converts string to floating-point number and advances str past the end
|
||||
// of the parsed input.
|
||||
double strtod(const char*& str) const {
|
||||
char* end = nullptr;
|
||||
double result = strtod_l(str, &end, locale_);
|
||||
str = end;
|
||||
return result;
|
||||
}
|
||||
};
|
||||
#endif // FMT_LOCALE
|
||||
FMT_END_NAMESPACE
|
||||
|
||||
#endif // FMT_POSIX_H_
|
||||
#include "os.h"
|
||||
#warning "fmt/posix.h is deprecated; use fmt/os.h instead"
|
@@ -1,4 +1,4 @@
|
||||
// Formatting library for C++
|
||||
// Formatting library for C++ - legacy printf implementation
|
||||
//
|
||||
// Copyright (c) 2012 - 2016, Victor Zverovich
|
||||
// All rights reserved.
|
||||
@@ -8,7 +8,7 @@
|
||||
#ifndef FMT_PRINTF_H_
|
||||
#define FMT_PRINTF_H_
|
||||
|
||||
#include <algorithm> // std::fill_n
|
||||
#include <algorithm> // std::max
|
||||
#include <limits> // std::numeric_limits
|
||||
|
||||
#include "ostream.h"
|
||||
@@ -16,15 +16,11 @@
|
||||
FMT_BEGIN_NAMESPACE
|
||||
namespace internal {
|
||||
|
||||
// A helper function to suppress bogus "conditional expression is constant"
|
||||
// warnings.
|
||||
template <typename T> inline T const_check(T value) { return value; }
|
||||
|
||||
// Checks if a value fits in int - used to avoid warnings about comparing
|
||||
// signed and unsigned integers.
|
||||
template <bool IsSigned> struct int_checker {
|
||||
template <typename T> static bool fits_in_int(T value) {
|
||||
unsigned max = std::numeric_limits<int>::max();
|
||||
unsigned max = max_value<int>();
|
||||
return value <= max;
|
||||
}
|
||||
static bool fits_in_int(bool) { return true; }
|
||||
@@ -32,8 +28,8 @@ template <bool IsSigned> struct int_checker {
|
||||
|
||||
template <> struct int_checker<true> {
|
||||
template <typename T> static bool fits_in_int(T value) {
|
||||
return value >= std::numeric_limits<int>::min() &&
|
||||
value <= std::numeric_limits<int>::max();
|
||||
return value >= (std::numeric_limits<int>::min)() &&
|
||||
value <= max_value<int>();
|
||||
}
|
||||
static bool fits_in_int(int) { return true; }
|
||||
};
|
||||
@@ -158,12 +154,12 @@ template <typename Char> class printf_width_handler {
|
||||
|
||||
template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
|
||||
unsigned operator()(T value) {
|
||||
auto width = static_cast<uint32_or_64_t<T>>(value);
|
||||
auto width = static_cast<uint32_or_64_or_128_t<T>>(value);
|
||||
if (internal::is_negative(value)) {
|
||||
specs_.align = align::left;
|
||||
width = 0 - width;
|
||||
}
|
||||
unsigned int_max = std::numeric_limits<int>::max();
|
||||
unsigned int_max = max_value<int>();
|
||||
if (width > int_max) FMT_THROW(format_error("number is too big"));
|
||||
return static_cast<unsigned>(width);
|
||||
}
|
||||
@@ -193,6 +189,10 @@ using internal::printf; // For printing into memory_buffer.
|
||||
|
||||
template <typename Range> class printf_arg_formatter;
|
||||
|
||||
template <typename Char>
|
||||
class basic_printf_parse_context : public basic_format_parse_context<Char> {
|
||||
using basic_format_parse_context<Char>::basic_format_parse_context;
|
||||
};
|
||||
template <typename OutputIt, typename Char> class basic_printf_context;
|
||||
|
||||
/**
|
||||
@@ -235,7 +235,7 @@ class printf_arg_formatter : public internal::arg_formatter_base<Range> {
|
||||
printf_arg_formatter(iterator iter, format_specs& specs, context_type& ctx)
|
||||
: base(Range(iter), &specs, internal::locale_ref()), context_(ctx) {}
|
||||
|
||||
template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
|
||||
template <typename T, FMT_ENABLE_IF(fmt::internal::is_integral<T>::value)>
|
||||
iterator operator()(T value) {
|
||||
// MSVC2013 fails to compile separate overloads for bool and char_type so
|
||||
// use std::is_same instead.
|
||||
@@ -307,6 +307,8 @@ class printf_arg_formatter : public internal::arg_formatter_base<Range> {
|
||||
};
|
||||
|
||||
template <typename T> struct printf_formatter {
|
||||
printf_formatter() = delete;
|
||||
|
||||
template <typename ParseContext>
|
||||
auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
|
||||
return ctx.begin();
|
||||
@@ -324,7 +326,9 @@ template <typename OutputIt, typename Char> class basic_printf_context {
|
||||
public:
|
||||
/** The character type for the output. */
|
||||
using char_type = Char;
|
||||
using iterator = OutputIt;
|
||||
using format_arg = basic_format_arg<basic_printf_context>;
|
||||
using parse_context_type = basic_printf_parse_context<Char>;
|
||||
template <typename T> using formatter_type = printf_formatter<T>;
|
||||
|
||||
private:
|
||||
@@ -332,17 +336,17 @@ template <typename OutputIt, typename Char> class basic_printf_context {
|
||||
|
||||
OutputIt out_;
|
||||
basic_format_args<basic_printf_context> args_;
|
||||
basic_parse_context<Char> parse_ctx_;
|
||||
parse_context_type parse_ctx_;
|
||||
|
||||
static void parse_flags(format_specs& specs, const Char*& it,
|
||||
const Char* end);
|
||||
|
||||
// Returns the argument with specified index or, if arg_index is equal
|
||||
// to the maximum unsigned value, the next argument.
|
||||
format_arg get_arg(unsigned arg_index = std::numeric_limits<unsigned>::max());
|
||||
// Returns the argument with specified index or, if arg_index is -1, the next
|
||||
// argument.
|
||||
format_arg get_arg(int arg_index = -1);
|
||||
|
||||
// Parses argument index, flags and width and returns the argument index.
|
||||
unsigned parse_header(const Char*& it, const Char* end, format_specs& specs);
|
||||
int parse_header(const Char*& it, const Char* end, format_specs& specs);
|
||||
|
||||
public:
|
||||
/**
|
||||
@@ -359,17 +363,18 @@ template <typename OutputIt, typename Char> class basic_printf_context {
|
||||
OutputIt out() { return out_; }
|
||||
void advance_to(OutputIt it) { out_ = it; }
|
||||
|
||||
format_arg arg(unsigned id) const { return args_.get(id); }
|
||||
internal::locale_ref locale() { return {}; }
|
||||
|
||||
basic_parse_context<Char>& parse_context() { return parse_ctx_; }
|
||||
format_arg arg(int id) const { return args_.get(id); }
|
||||
|
||||
parse_context_type& parse_context() { return parse_ctx_; }
|
||||
|
||||
FMT_CONSTEXPR void on_error(const char* message) {
|
||||
parse_ctx_.on_error(message);
|
||||
}
|
||||
|
||||
/** Formats stored arguments and writes the output to the range. */
|
||||
template <typename ArgFormatter =
|
||||
printf_arg_formatter<internal::buffer_range<Char>>>
|
||||
template <typename ArgFormatter = printf_arg_formatter<buffer_range<Char>>>
|
||||
OutputIt format();
|
||||
};
|
||||
|
||||
@@ -402,8 +407,8 @@ void basic_printf_context<OutputIt, Char>::parse_flags(format_specs& specs,
|
||||
|
||||
template <typename OutputIt, typename Char>
|
||||
typename basic_printf_context<OutputIt, Char>::format_arg
|
||||
basic_printf_context<OutputIt, Char>::get_arg(unsigned arg_index) {
|
||||
if (arg_index == std::numeric_limits<unsigned>::max())
|
||||
basic_printf_context<OutputIt, Char>::get_arg(int arg_index) {
|
||||
if (arg_index < 0)
|
||||
arg_index = parse_ctx_.next_arg_id();
|
||||
else
|
||||
parse_ctx_.check_arg_id(--arg_index);
|
||||
@@ -411,15 +416,16 @@ basic_printf_context<OutputIt, Char>::get_arg(unsigned arg_index) {
|
||||
}
|
||||
|
||||
template <typename OutputIt, typename Char>
|
||||
unsigned basic_printf_context<OutputIt, Char>::parse_header(
|
||||
const Char*& it, const Char* end, format_specs& specs) {
|
||||
unsigned arg_index = std::numeric_limits<unsigned>::max();
|
||||
int basic_printf_context<OutputIt, Char>::parse_header(const Char*& it,
|
||||
const Char* end,
|
||||
format_specs& specs) {
|
||||
int arg_index = -1;
|
||||
char_type c = *it;
|
||||
if (c >= '0' && c <= '9') {
|
||||
// Parse an argument index (if followed by '$') or a width possibly
|
||||
// preceded with '0' flag(s).
|
||||
internal::error_handler eh;
|
||||
unsigned value = parse_nonnegative_int(it, end, eh);
|
||||
int value = parse_nonnegative_int(it, end, eh);
|
||||
if (it != end && *it == '$') { // value is an argument index
|
||||
++it;
|
||||
arg_index = value;
|
||||
@@ -441,8 +447,8 @@ unsigned basic_printf_context<OutputIt, Char>::parse_header(
|
||||
specs.width = parse_nonnegative_int(it, end, eh);
|
||||
} else if (*it == '*') {
|
||||
++it;
|
||||
specs.width = visit_format_arg(
|
||||
internal::printf_width_handler<char_type>(specs), get_arg());
|
||||
specs.width = static_cast<int>(visit_format_arg(
|
||||
internal::printf_width_handler<char_type>(specs), get_arg()));
|
||||
}
|
||||
}
|
||||
return arg_index;
|
||||
@@ -469,7 +475,8 @@ OutputIt basic_printf_context<OutputIt, Char>::format() {
|
||||
specs.align = align::right;
|
||||
|
||||
// Parse argument index, flags and width.
|
||||
unsigned arg_index = parse_header(it, end, specs);
|
||||
int arg_index = parse_header(it, end, specs);
|
||||
if (arg_index == 0) on_error("argument index out of range");
|
||||
|
||||
// Parse precision.
|
||||
if (it != end && *it == '.') {
|
||||
@@ -477,11 +484,11 @@ OutputIt basic_printf_context<OutputIt, Char>::format() {
|
||||
c = it != end ? *it : 0;
|
||||
if ('0' <= c && c <= '9') {
|
||||
internal::error_handler eh;
|
||||
specs.precision = static_cast<int>(parse_nonnegative_int(it, end, eh));
|
||||
specs.precision = parse_nonnegative_int(it, end, eh);
|
||||
} else if (c == '*') {
|
||||
++it;
|
||||
specs.precision =
|
||||
visit_format_arg(internal::printf_precision_handler(), get_arg());
|
||||
specs.precision = static_cast<int>(
|
||||
visit_format_arg(internal::printf_precision_handler(), get_arg()));
|
||||
} else {
|
||||
specs.precision = 0;
|
||||
}
|
||||
@@ -600,7 +607,8 @@ inline format_arg_store<wprintf_context, Args...> make_wprintf_args(
|
||||
|
||||
template <typename S, typename Char = char_t<S>>
|
||||
inline std::basic_string<Char> vsprintf(
|
||||
const S& format, basic_format_args<basic_printf_context_t<Char>> args) {
|
||||
const S& format,
|
||||
basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) {
|
||||
basic_memory_buffer<Char> buffer;
|
||||
printf(buffer, to_string_view(format), args);
|
||||
return to_string(buffer);
|
||||
@@ -619,12 +627,13 @@ template <typename S, typename... Args,
|
||||
typename Char = enable_if_t<internal::is_string<S>::value, char_t<S>>>
|
||||
inline std::basic_string<Char> sprintf(const S& format, const Args&... args) {
|
||||
using context = basic_printf_context_t<Char>;
|
||||
return vsprintf(to_string_view(format), {make_format_args<context>(args...)});
|
||||
return vsprintf(to_string_view(format), make_format_args<context>(args...));
|
||||
}
|
||||
|
||||
template <typename S, typename Char = char_t<S>>
|
||||
inline int vfprintf(std::FILE* f, const S& format,
|
||||
basic_format_args<basic_printf_context_t<Char>> args) {
|
||||
inline int vfprintf(
|
||||
std::FILE* f, const S& format,
|
||||
basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) {
|
||||
basic_memory_buffer<Char> buffer;
|
||||
printf(buffer, to_string_view(format), args);
|
||||
std::size_t size = buffer.size();
|
||||
@@ -647,12 +656,13 @@ template <typename S, typename... Args,
|
||||
inline int fprintf(std::FILE* f, const S& format, const Args&... args) {
|
||||
using context = basic_printf_context_t<Char>;
|
||||
return vfprintf(f, to_string_view(format),
|
||||
{make_format_args<context>(args...)});
|
||||
make_format_args<context>(args...));
|
||||
}
|
||||
|
||||
template <typename S, typename Char = char_t<S>>
|
||||
inline int vprintf(const S& format,
|
||||
basic_format_args<basic_printf_context_t<Char>> args) {
|
||||
inline int vprintf(
|
||||
const S& format,
|
||||
basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) {
|
||||
return vfprintf(stdout, to_string_view(format), args);
|
||||
}
|
||||
|
||||
@@ -670,12 +680,13 @@ template <typename S, typename... Args,
|
||||
inline int printf(const S& format_str, const Args&... args) {
|
||||
using context = basic_printf_context_t<char_t<S>>;
|
||||
return vprintf(to_string_view(format_str),
|
||||
{make_format_args<context>(args...)});
|
||||
make_format_args<context>(args...));
|
||||
}
|
||||
|
||||
template <typename S, typename Char = char_t<S>>
|
||||
inline int vfprintf(std::basic_ostream<Char>& os, const S& format,
|
||||
basic_format_args<basic_printf_context_t<Char>> args) {
|
||||
inline int vfprintf(
|
||||
std::basic_ostream<Char>& os, const S& format,
|
||||
basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) {
|
||||
basic_memory_buffer<Char> buffer;
|
||||
printf(buffer, to_string_view(format), args);
|
||||
internal::write(os, buffer);
|
||||
@@ -686,9 +697,9 @@ inline int vfprintf(std::basic_ostream<Char>& os, const S& format,
|
||||
template <typename ArgFormatter, typename Char,
|
||||
typename Context =
|
||||
basic_printf_context<typename ArgFormatter::iterator, Char>>
|
||||
typename ArgFormatter::iterator vprintf(internal::buffer<Char>& out,
|
||||
basic_string_view<Char> format_str,
|
||||
basic_format_args<Context> args) {
|
||||
typename ArgFormatter::iterator vprintf(
|
||||
internal::buffer<Char>& out, basic_string_view<Char> format_str,
|
||||
basic_format_args<type_identity_t<Context>> args) {
|
||||
typename ArgFormatter::iterator iter(out);
|
||||
Context(iter, format_str, args).template format<ArgFormatter>();
|
||||
return iter;
|
||||
@@ -708,7 +719,7 @@ inline int fprintf(std::basic_ostream<Char>& os, const S& format_str,
|
||||
const Args&... args) {
|
||||
using context = basic_printf_context_t<Char>;
|
||||
return vfprintf(os, to_string_view(format_str),
|
||||
{make_format_args<context>(args...)});
|
||||
make_format_args<context>(args...));
|
||||
}
|
||||
FMT_END_NAMESPACE
|
||||
|
||||
|
@@ -12,7 +12,9 @@
|
||||
#ifndef FMT_RANGES_H_
|
||||
#define FMT_RANGES_H_
|
||||
|
||||
#include <initializer_list>
|
||||
#include <type_traits>
|
||||
|
||||
#include "format.h"
|
||||
|
||||
// output only up to N items from the range.
|
||||
@@ -104,10 +106,7 @@ struct is_range_<
|
||||
/// tuple_size and tuple_element check.
|
||||
template <typename T> class is_tuple_like_ {
|
||||
template <typename U>
|
||||
static auto check(U* p)
|
||||
-> decltype(std::tuple_size<U>::value,
|
||||
(void)std::declval<typename std::tuple_element<0, U>::type>(),
|
||||
int());
|
||||
static auto check(U* p) -> decltype(std::tuple_size<U>::value, int());
|
||||
template <typename> static void check(...);
|
||||
|
||||
public:
|
||||
@@ -246,7 +245,8 @@ template <typename T, typename Char> struct is_range {
|
||||
static FMT_CONSTEXPR_DECL const bool value =
|
||||
internal::is_range_<T>::value &&
|
||||
!internal::is_like_std_string<T>::value &&
|
||||
!std::is_convertible<T, std::basic_string<Char>>::value;
|
||||
!std::is_convertible<T, std::basic_string<Char>>::value &&
|
||||
!std::is_constructible<internal::std_string_view<Char>, T>::value;
|
||||
};
|
||||
|
||||
template <typename RangeT, typename Char>
|
||||
@@ -283,6 +283,105 @@ struct formatter<RangeT, Char,
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Char, typename... T> struct tuple_arg_join : internal::view {
|
||||
const std::tuple<T...>& tuple;
|
||||
basic_string_view<Char> sep;
|
||||
|
||||
tuple_arg_join(const std::tuple<T...>& t, basic_string_view<Char> s)
|
||||
: tuple{t}, sep{s} {}
|
||||
};
|
||||
|
||||
template <typename Char, typename... T>
|
||||
struct formatter<tuple_arg_join<Char, T...>, Char> {
|
||||
template <typename ParseContext>
|
||||
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
|
||||
return ctx.begin();
|
||||
}
|
||||
|
||||
template <typename FormatContext>
|
||||
typename FormatContext::iterator format(
|
||||
const tuple_arg_join<Char, T...>& value, FormatContext& ctx) {
|
||||
return format(value, ctx, internal::make_index_sequence<sizeof...(T)>{});
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename FormatContext, size_t... N>
|
||||
typename FormatContext::iterator format(
|
||||
const tuple_arg_join<Char, T...>& value, FormatContext& ctx,
|
||||
internal::index_sequence<N...>) {
|
||||
return format_args(value, ctx, std::get<N>(value.tuple)...);
|
||||
}
|
||||
|
||||
template <typename FormatContext>
|
||||
typename FormatContext::iterator format_args(
|
||||
const tuple_arg_join<Char, T...>&, FormatContext& ctx) {
|
||||
// NOTE: for compilers that support C++17, this empty function instantiation
|
||||
// can be replaced with a constexpr branch in the variadic overload.
|
||||
return ctx.out();
|
||||
}
|
||||
|
||||
template <typename FormatContext, typename Arg, typename... Args>
|
||||
typename FormatContext::iterator format_args(
|
||||
const tuple_arg_join<Char, T...>& value, FormatContext& ctx,
|
||||
const Arg& arg, const Args&... args) {
|
||||
using base = formatter<typename std::decay<Arg>::type, Char>;
|
||||
auto out = ctx.out();
|
||||
out = base{}.format(arg, ctx);
|
||||
if (sizeof...(Args) > 0) {
|
||||
out = std::copy(value.sep.begin(), value.sep.end(), out);
|
||||
ctx.advance_to(out);
|
||||
return format_args(value, ctx, args...);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
\rst
|
||||
Returns an object that formats `tuple` with elements separated by `sep`.
|
||||
|
||||
**Example**::
|
||||
|
||||
std::tuple<int, char> t = {1, 'a'};
|
||||
fmt::print("{}", fmt::join(t, ", "));
|
||||
// Output: "1, a"
|
||||
\endrst
|
||||
*/
|
||||
template <typename... T>
|
||||
FMT_CONSTEXPR tuple_arg_join<char, T...> join(const std::tuple<T...>& tuple,
|
||||
string_view sep) {
|
||||
return {tuple, sep};
|
||||
}
|
||||
|
||||
template <typename... T>
|
||||
FMT_CONSTEXPR tuple_arg_join<wchar_t, T...> join(const std::tuple<T...>& tuple,
|
||||
wstring_view sep) {
|
||||
return {tuple, sep};
|
||||
}
|
||||
|
||||
/**
|
||||
\rst
|
||||
Returns an object that formats `initializer_list` with elements separated by
|
||||
`sep`.
|
||||
|
||||
**Example**::
|
||||
|
||||
fmt::print("{}", fmt::join({1, 2, 3}, ", "));
|
||||
// Output: "1, 2, 3"
|
||||
\endrst
|
||||
*/
|
||||
template <typename T>
|
||||
arg_join<internal::iterator_t<const std::initializer_list<T>>, char> join(
|
||||
std::initializer_list<T> list, string_view sep) {
|
||||
return join(std::begin(list), std::end(list), sep);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
arg_join<internal::iterator_t<const std::initializer_list<T>>, wchar_t> join(
|
||||
std::initializer_list<T> list, wstring_view sep) {
|
||||
return join(std::begin(list), std::end(list), sep);
|
||||
}
|
||||
|
||||
FMT_END_NAMESPACE
|
||||
|
||||
#endif // FMT_RANGES_H_
|
||||
|
@@ -1,293 +0,0 @@
|
||||
/*
|
||||
* For conversion between std::chrono::durations without undefined
|
||||
* behaviour or erroneous results.
|
||||
* This is a stripped down version of duration_cast, for inclusion in fmt.
|
||||
* See https://github.com/pauldreik/safe_duration_cast
|
||||
*
|
||||
* Copyright Paul Dreik 2019
|
||||
*
|
||||
* This file is licensed under the fmt license, see format.h
|
||||
*/
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <type_traits>
|
||||
|
||||
#include "format.h"
|
||||
|
||||
FMT_BEGIN_NAMESPACE
|
||||
|
||||
namespace safe_duration_cast {
|
||||
|
||||
template <typename To, typename From,
|
||||
FMT_ENABLE_IF(!std::is_same<From, To>::value &&
|
||||
std::numeric_limits<From>::is_signed ==
|
||||
std::numeric_limits<To>::is_signed)>
|
||||
FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
|
||||
ec = 0;
|
||||
using F = std::numeric_limits<From>;
|
||||
using T = std::numeric_limits<To>;
|
||||
static_assert(F::is_integer, "From must be integral");
|
||||
static_assert(T::is_integer, "To must be integral");
|
||||
|
||||
// A and B are both signed, or both unsigned.
|
||||
if (F::digits <= T::digits) {
|
||||
// From fits in To without any problem.
|
||||
} else {
|
||||
// From does not always fit in To, resort to a dynamic check.
|
||||
if (from < T::min() || from > T::max()) {
|
||||
// outside range.
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
}
|
||||
return static_cast<To>(from);
|
||||
}
|
||||
|
||||
/**
|
||||
* converts From to To, without loss. If the dynamic value of from
|
||||
* can't be converted to To without loss, ec is set.
|
||||
*/
|
||||
template <typename To, typename From,
|
||||
FMT_ENABLE_IF(!std::is_same<From, To>::value &&
|
||||
std::numeric_limits<From>::is_signed !=
|
||||
std::numeric_limits<To>::is_signed)>
|
||||
FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
|
||||
ec = 0;
|
||||
using F = std::numeric_limits<From>;
|
||||
using T = std::numeric_limits<To>;
|
||||
static_assert(F::is_integer, "From must be integral");
|
||||
static_assert(T::is_integer, "To must be integral");
|
||||
|
||||
if (F::is_signed && !T::is_signed) {
|
||||
// From may be negative, not allowed!
|
||||
if (from < 0) {
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
|
||||
// From is positive. Can it always fit in To?
|
||||
if (F::digits <= T::digits) {
|
||||
// yes, From always fits in To.
|
||||
} else {
|
||||
// from may not fit in To, we have to do a dynamic check
|
||||
if (from > static_cast<From>(T::max())) {
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!F::is_signed && T::is_signed) {
|
||||
// can from be held in To?
|
||||
if (F::digits < T::digits) {
|
||||
// yes, From always fits in To.
|
||||
} else {
|
||||
// from may not fit in To, we have to do a dynamic check
|
||||
if (from > static_cast<From>(T::max())) {
|
||||
// outside range.
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// reaching here means all is ok for lossless conversion.
|
||||
return static_cast<To>(from);
|
||||
|
||||
} // function
|
||||
|
||||
template <typename To, typename From,
|
||||
FMT_ENABLE_IF(std::is_same<From, To>::value)>
|
||||
FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
|
||||
ec = 0;
|
||||
return from;
|
||||
} // function
|
||||
|
||||
// clang-format off
|
||||
/**
|
||||
* converts From to To if possible, otherwise ec is set.
|
||||
*
|
||||
* input | output
|
||||
* ---------------------------------|---------------
|
||||
* NaN | NaN
|
||||
* Inf | Inf
|
||||
* normal, fits in output | converted (possibly lossy)
|
||||
* normal, does not fit in output | ec is set
|
||||
* subnormal | best effort
|
||||
* -Inf | -Inf
|
||||
*/
|
||||
// clang-format on
|
||||
template <typename To, typename From,
|
||||
FMT_ENABLE_IF(!std::is_same<From, To>::value)>
|
||||
FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) {
|
||||
ec = 0;
|
||||
using T = std::numeric_limits<To>;
|
||||
static_assert(std::is_floating_point<From>::value, "From must be floating");
|
||||
static_assert(std::is_floating_point<To>::value, "To must be floating");
|
||||
|
||||
// catch the only happy case
|
||||
if (std::isfinite(from)) {
|
||||
if (from >= T::lowest() && from <= T::max()) {
|
||||
return static_cast<To>(from);
|
||||
}
|
||||
// not within range.
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
|
||||
// nan and inf will be preserved
|
||||
return static_cast<To>(from);
|
||||
} // function
|
||||
|
||||
template <typename To, typename From,
|
||||
FMT_ENABLE_IF(std::is_same<From, To>::value)>
|
||||
FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) {
|
||||
ec = 0;
|
||||
static_assert(std::is_floating_point<From>::value, "From must be floating");
|
||||
return from;
|
||||
}
|
||||
|
||||
/**
|
||||
* safe duration cast between integral durations
|
||||
*/
|
||||
template <typename To, typename FromRep, typename FromPeriod,
|
||||
FMT_ENABLE_IF(std::is_integral<FromRep>::value),
|
||||
FMT_ENABLE_IF(std::is_integral<typename To::rep>::value)>
|
||||
To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
|
||||
int& ec) {
|
||||
using From = std::chrono::duration<FromRep, FromPeriod>;
|
||||
ec = 0;
|
||||
// the basic idea is that we need to convert from count() in the from type
|
||||
// to count() in the To type, by multiplying it with this:
|
||||
using Factor = std::ratio_divide<typename From::period, typename To::period>;
|
||||
|
||||
static_assert(Factor::num > 0, "num must be positive");
|
||||
static_assert(Factor::den > 0, "den must be positive");
|
||||
|
||||
// the conversion is like this: multiply from.count() with Factor::num
|
||||
// /Factor::den and convert it to To::rep, all this without
|
||||
// overflow/underflow. let's start by finding a suitable type that can hold
|
||||
// both To, From and Factor::num
|
||||
using IntermediateRep =
|
||||
typename std::common_type<typename From::rep, typename To::rep,
|
||||
decltype(Factor::num)>::type;
|
||||
|
||||
// safe conversion to IntermediateRep
|
||||
IntermediateRep count =
|
||||
lossless_integral_conversion<IntermediateRep>(from.count(), ec);
|
||||
if (ec) {
|
||||
return {};
|
||||
}
|
||||
// multiply with Factor::num without overflow or underflow
|
||||
if (Factor::num != 1) {
|
||||
constexpr auto max1 =
|
||||
std::numeric_limits<IntermediateRep>::max() / Factor::num;
|
||||
if (count > max1) {
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
constexpr auto min1 =
|
||||
std::numeric_limits<IntermediateRep>::min() / Factor::num;
|
||||
if (count < min1) {
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
count *= Factor::num;
|
||||
}
|
||||
|
||||
// this can't go wrong, right? den>0 is checked earlier.
|
||||
if (Factor::den != 1) {
|
||||
count /= Factor::den;
|
||||
}
|
||||
// convert to the to type, safely
|
||||
using ToRep = typename To::rep;
|
||||
const ToRep tocount = lossless_integral_conversion<ToRep>(count, ec);
|
||||
if (ec) {
|
||||
return {};
|
||||
}
|
||||
return To{tocount};
|
||||
}
|
||||
|
||||
/**
|
||||
* safe duration_cast between floating point durations
|
||||
*/
|
||||
template <typename To, typename FromRep, typename FromPeriod,
|
||||
FMT_ENABLE_IF(std::is_floating_point<FromRep>::value),
|
||||
FMT_ENABLE_IF(std::is_floating_point<typename To::rep>::value)>
|
||||
To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
|
||||
int& ec) {
|
||||
using From = std::chrono::duration<FromRep, FromPeriod>;
|
||||
ec = 0;
|
||||
if (std::isnan(from.count())) {
|
||||
// nan in, gives nan out. easy.
|
||||
return To{std::numeric_limits<typename To::rep>::quiet_NaN()};
|
||||
}
|
||||
// maybe we should also check if from is denormal, and decide what to do about
|
||||
// it.
|
||||
|
||||
// +-inf should be preserved.
|
||||
if (std::isinf(from.count())) {
|
||||
return To{from.count()};
|
||||
}
|
||||
|
||||
// the basic idea is that we need to convert from count() in the from type
|
||||
// to count() in the To type, by multiplying it with this:
|
||||
using Factor = std::ratio_divide<typename From::period, typename To::period>;
|
||||
|
||||
static_assert(Factor::num > 0, "num must be positive");
|
||||
static_assert(Factor::den > 0, "den must be positive");
|
||||
|
||||
// the conversion is like this: multiply from.count() with Factor::num
|
||||
// /Factor::den and convert it to To::rep, all this without
|
||||
// overflow/underflow. let's start by finding a suitable type that can hold
|
||||
// both To, From and Factor::num
|
||||
using IntermediateRep =
|
||||
typename std::common_type<typename From::rep, typename To::rep,
|
||||
decltype(Factor::num)>::type;
|
||||
|
||||
// force conversion of From::rep -> IntermediateRep to be safe,
|
||||
// even if it will never happen be narrowing in this context.
|
||||
IntermediateRep count =
|
||||
safe_float_conversion<IntermediateRep>(from.count(), ec);
|
||||
if (ec) {
|
||||
return {};
|
||||
}
|
||||
|
||||
// multiply with Factor::num without overflow or underflow
|
||||
if (Factor::num != 1) {
|
||||
constexpr auto max1 = std::numeric_limits<IntermediateRep>::max() /
|
||||
static_cast<IntermediateRep>(Factor::num);
|
||||
if (count > max1) {
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
constexpr auto min1 = std::numeric_limits<IntermediateRep>::lowest() /
|
||||
static_cast<IntermediateRep>(Factor::num);
|
||||
if (count < min1) {
|
||||
ec = 1;
|
||||
return {};
|
||||
}
|
||||
count *= static_cast<IntermediateRep>(Factor::num);
|
||||
}
|
||||
|
||||
// this can't go wrong, right? den>0 is checked earlier.
|
||||
if (Factor::den != 1) {
|
||||
using common_t = typename std::common_type<IntermediateRep, intmax_t>::type;
|
||||
count /= static_cast<common_t>(Factor::den);
|
||||
}
|
||||
|
||||
// convert to the to type, safely
|
||||
using ToRep = typename To::rep;
|
||||
|
||||
const ToRep tocount = safe_float_conversion<ToRep>(count, ec);
|
||||
if (ec) {
|
||||
return {};
|
||||
}
|
||||
return To{tocount};
|
||||
}
|
||||
|
||||
} // namespace safe_duration_cast
|
||||
|
||||
FMT_END_NAMESPACE
|
@@ -11,17 +11,15 @@
|
||||
//
|
||||
|
||||
#if !defined(SPDLOG_FMT_EXTERNAL)
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
#ifndef FMT_HEADER_ONLY
|
||||
#if !defined(SPDLOG_COMPILED_LIB) && !defined(FMT_HEADER_ONLY)
|
||||
#define FMT_HEADER_ONLY
|
||||
#endif
|
||||
#endif
|
||||
#ifndef FMT_USE_WINDOWS_H
|
||||
#define FMT_USE_WINDOWS_H 0
|
||||
#endif
|
||||
#include "bundled/core.h"
|
||||
#include "bundled/format.h"
|
||||
#include <spdlog/fmt/bundled/core.h>
|
||||
#include <spdlog/fmt/bundled/format.h>
|
||||
#else // SPDLOG_FMT_EXTERNAL is defined - use external fmtlib
|
||||
#include "fmt/core.h"
|
||||
#include "fmt/format.h"
|
||||
#endif
|
||||
#include <fmt/core.h>
|
||||
#include <fmt/format.h>
|
||||
#endif
|
@@ -7,12 +7,14 @@
|
||||
//
|
||||
// include bundled or external copy of fmtlib's ostream support
|
||||
//
|
||||
|
||||
#if !defined(SPDLOG_FMT_EXTERNAL)
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
#ifndef FMT_HEADER_ONLY
|
||||
#define FMT_HEADER_ONLY
|
||||
#endif
|
||||
#include "bundled/ostream.h"
|
||||
#include "fmt.h"
|
||||
#endif
|
||||
#include <spdlog/fmt/bundled/ostream.h>
|
||||
#else
|
||||
#include <fmt/ostream.h>
|
||||
#endif
|
||||
|
@@ -3,8 +3,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "fmt/fmt.h"
|
||||
#include "spdlog/details/log_msg.h"
|
||||
#include <spdlog/fmt/fmt.h>
|
||||
#include <spdlog/details/log_msg.h>
|
||||
|
||||
namespace spdlog {
|
||||
|
||||
|
14
include/spdlog/fwd.h
Normal file
14
include/spdlog/fwd.h
Normal file
@@ -0,0 +1,14 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace spdlog {
|
||||
class logger;
|
||||
class formatter;
|
||||
|
||||
namespace sinks {
|
||||
class sink;
|
||||
}
|
||||
|
||||
} // namespace spdlog
|
@@ -4,12 +4,12 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/logger.h"
|
||||
#include <spdlog/logger.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/sinks/sink.h"
|
||||
#include "spdlog/details/backtracer.h"
|
||||
#include "spdlog/details/pattern_formatter.h"
|
||||
#include <spdlog/sinks/sink.h>
|
||||
#include <spdlog/details/backtracer.h>
|
||||
#include <spdlog/pattern_formatter.h>
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
@@ -64,11 +64,6 @@ SPDLOG_INLINE void swap(logger &a, logger &b)
|
||||
a.swap(b);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE bool logger::should_log(level::level_enum msg_level) const
|
||||
{
|
||||
return msg_level >= level_.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void logger::set_level(level::level_enum log_level)
|
||||
{
|
||||
level_.store(log_level);
|
||||
@@ -85,7 +80,7 @@ SPDLOG_INLINE const std::string &logger::name() const
|
||||
}
|
||||
|
||||
// set formatting for the sinks in this logger.
|
||||
// each sink will get a seperate instance of the formatter object.
|
||||
// each sink will get a separate instance of the formatter object.
|
||||
SPDLOG_INLINE void logger::set_formatter(std::unique_ptr<formatter> f)
|
||||
{
|
||||
for (auto it = sinks_.begin(); it != sinks_.end(); ++it)
|
||||
@@ -94,6 +89,7 @@ SPDLOG_INLINE void logger::set_formatter(std::unique_ptr<formatter> f)
|
||||
{
|
||||
// last element - we can be move it.
|
||||
(*it)->set_formatter(std::move(f));
|
||||
break; // to prevent clang-tidy warning
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -155,7 +151,7 @@ SPDLOG_INLINE std::vector<sink_ptr> &logger::sinks()
|
||||
// error handler
|
||||
SPDLOG_INLINE void logger::set_error_handler(err_handler handler)
|
||||
{
|
||||
custom_err_handler_ = handler;
|
||||
custom_err_handler_ = std::move(handler);
|
||||
}
|
||||
|
||||
// create new logger with same sinks and configuration.
|
||||
@@ -167,6 +163,18 @@ SPDLOG_INLINE std::shared_ptr<logger> logger::clone(std::string logger_name)
|
||||
}
|
||||
|
||||
// protected methods
|
||||
SPDLOG_INLINE void logger::log_it_(const spdlog::details::log_msg &log_msg, bool log_enabled, bool traceback_enabled)
|
||||
{
|
||||
if (log_enabled)
|
||||
{
|
||||
sink_it_(log_msg);
|
||||
}
|
||||
if (traceback_enabled)
|
||||
{
|
||||
tracer_.push_back(log_msg);
|
||||
}
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void logger::sink_it_(const details::log_msg &msg)
|
||||
{
|
||||
for (auto &sink : sinks_)
|
||||
@@ -202,10 +210,10 @@ SPDLOG_INLINE void logger::flush_()
|
||||
SPDLOG_INLINE void logger::dump_backtrace_()
|
||||
{
|
||||
using details::log_msg;
|
||||
if (tracer_)
|
||||
if (tracer_.enabled())
|
||||
{
|
||||
sink_it_(log_msg{name(), level::info, "****************** Backtrace Start ******************"});
|
||||
tracer_.foreach_pop([this](const details::log_msg &msg) { this->sink_it_(msg); });
|
||||
tracer_.foreach_pop([this](const log_msg &msg) { this->sink_it_(msg); });
|
||||
sink_it_(log_msg{name(), level::info, "****************** Backtrace End ********************"});
|
||||
}
|
||||
}
|
||||
@@ -218,7 +226,6 @@ SPDLOG_INLINE bool logger::should_flush_(const details::log_msg &msg)
|
||||
|
||||
SPDLOG_INLINE void logger::err_handler_(const std::string &msg)
|
||||
{
|
||||
|
||||
if (custom_err_handler_)
|
||||
{
|
||||
custom_err_handler_(msg);
|
||||
|
@@ -3,8 +3,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
// Thread safe logger (except for set_pattern(..), set_formatter(..) and
|
||||
// set_error_handler())
|
||||
// Thread safe logger (except for set_error_handler())
|
||||
// Has name, log level, vector of std::shared sink pointers and formatter
|
||||
// Upon each log write the logger:
|
||||
// 1. Checks if its log level is enough to log the message and if yes:
|
||||
@@ -15,12 +14,12 @@
|
||||
// The use of private formatter per sink provides the opportunity to cache some
|
||||
// formatted data, and support for different format per sink.
|
||||
|
||||
#include "spdlog/common.h"
|
||||
#include "spdlog/details/log_msg.h"
|
||||
#include "spdlog/details/backtracer.h"
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/log_msg.h>
|
||||
#include <spdlog/details/backtracer.h>
|
||||
|
||||
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
|
||||
#include "spdlog/details/os.h"
|
||||
#include <spdlog/details/os.h>
|
||||
#endif
|
||||
|
||||
#include <vector>
|
||||
@@ -40,7 +39,7 @@
|
||||
|
||||
namespace spdlog {
|
||||
|
||||
class logger
|
||||
class SPDLOG_API logger
|
||||
{
|
||||
public:
|
||||
// Empty logger
|
||||
@@ -77,8 +76,9 @@ public:
|
||||
template<typename... Args>
|
||||
void log(source_loc loc, level::level_enum lvl, string_view_t fmt, const Args &... args)
|
||||
{
|
||||
auto level_enabled = should_log(lvl);
|
||||
if (!level_enabled && !tracer_)
|
||||
bool log_enabled = should_log(lvl);
|
||||
bool traceback_enabled = tracer_.enabled();
|
||||
if (!log_enabled && !traceback_enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -87,14 +87,7 @@ public:
|
||||
memory_buf_t buf;
|
||||
fmt::format_to(buf, fmt, args...);
|
||||
details::log_msg log_msg(loc, name_, lvl, string_view_t(buf.data(), buf.size()));
|
||||
if (level_enabled)
|
||||
{
|
||||
sink_it_(log_msg);
|
||||
}
|
||||
if (tracer_)
|
||||
{
|
||||
tracer_.push_back(log_msg);
|
||||
}
|
||||
log_it_(log_msg, log_enabled, traceback_enabled);
|
||||
}
|
||||
SPDLOG_LOGGER_CATCH()
|
||||
}
|
||||
@@ -151,24 +144,33 @@ public:
|
||||
template<class T, typename std::enable_if<std::is_convertible<const T &, spdlog::string_view_t>::value, T>::type * = nullptr>
|
||||
void log(source_loc loc, level::level_enum lvl, const T &msg)
|
||||
{
|
||||
auto level_enabled = should_log(lvl);
|
||||
if (!level_enabled && !tracer_)
|
||||
log(loc, lvl, string_view_t{msg});
|
||||
}
|
||||
|
||||
void log(log_clock::time_point log_time, source_loc loc, level::level_enum lvl, string_view_t msg)
|
||||
{
|
||||
bool log_enabled = should_log(lvl);
|
||||
bool traceback_enabled = tracer_.enabled();
|
||||
if (!log_enabled && !traceback_enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
SPDLOG_TRY
|
||||
|
||||
details::log_msg log_msg(log_time, loc, name_, lvl, msg);
|
||||
log_it_(log_msg, log_enabled, traceback_enabled);
|
||||
}
|
||||
|
||||
void log(source_loc loc, level::level_enum lvl, string_view_t msg)
|
||||
{
|
||||
bool log_enabled = should_log(lvl);
|
||||
bool traceback_enabled = tracer_.enabled();
|
||||
if (!log_enabled && !traceback_enabled)
|
||||
{
|
||||
details::log_msg log_msg(loc, name_, lvl, msg);
|
||||
if (level_enabled)
|
||||
{
|
||||
sink_it_(log_msg);
|
||||
}
|
||||
if (tracer_)
|
||||
{
|
||||
tracer_.push_back(log_msg);
|
||||
}
|
||||
return;
|
||||
}
|
||||
SPDLOG_LOGGER_CATCH()
|
||||
|
||||
details::log_msg log_msg(loc, name_, lvl, msg);
|
||||
log_it_(log_msg, log_enabled, traceback_enabled);
|
||||
}
|
||||
|
||||
void log(level::level_enum lvl, string_view_t msg)
|
||||
@@ -229,8 +231,9 @@ public:
|
||||
template<typename... Args>
|
||||
void log(source_loc loc, level::level_enum lvl, wstring_view_t fmt, const Args &... args)
|
||||
{
|
||||
auto level_enabled = should_log(lvl);
|
||||
if (!level_enabled && !tracer_)
|
||||
bool log_enabled = should_log(lvl);
|
||||
bool traceback_enabled = tracer_.enabled();
|
||||
if (!log_enabled && !traceback_enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -243,15 +246,7 @@ public:
|
||||
memory_buf_t buf;
|
||||
details::os::wstr_to_utf8buf(wstring_view_t(wbuf.data(), wbuf.size()), buf);
|
||||
details::log_msg log_msg(loc, name_, lvl, string_view_t(buf.data(), buf.size()));
|
||||
|
||||
if (level_enabled)
|
||||
{
|
||||
sink_it_(log_msg);
|
||||
}
|
||||
if (tracer_)
|
||||
{
|
||||
tracer_.push_back(log_msg);
|
||||
}
|
||||
log_it_(log_msg, log_enabled, traceback_enabled);
|
||||
}
|
||||
SPDLOG_LOGGER_CATCH()
|
||||
}
|
||||
@@ -302,25 +297,36 @@ public:
|
||||
template<class T, typename std::enable_if<is_convertible_to_wstring_view<const T &>::value, T>::type * = nullptr>
|
||||
void log(source_loc loc, level::level_enum lvl, const T &msg)
|
||||
{
|
||||
if (!should_log(lvl))
|
||||
bool log_enabled = should_log(lvl);
|
||||
bool traceback_enabled = tracer_.enabled();
|
||||
if (!log_enabled && !traceback_enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
SPDLOG_TRY
|
||||
{
|
||||
memory_buf_t buf;
|
||||
details::os::wstr_to_utf8buf(msg, buf);
|
||||
|
||||
details::log_msg log_msg(loc, name_, lvl, string_view_t(buf.data(), buf.size()));
|
||||
sink_it_(log_msg);
|
||||
log_it_(log_msg, log_enabled, traceback_enabled);
|
||||
}
|
||||
SPDLOG_LOGGER_CATCH()
|
||||
}
|
||||
#endif // _WIN32
|
||||
#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT
|
||||
|
||||
bool should_log(level::level_enum msg_level) const;
|
||||
// return true logging is enabled for the given level.
|
||||
bool should_log(level::level_enum msg_level) const
|
||||
{
|
||||
return msg_level >= level_.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
// return true if backtrace logging is enabled.
|
||||
bool should_backtrace() const
|
||||
{
|
||||
return tracer_.enabled();
|
||||
}
|
||||
|
||||
void set_level(level::level_enum log_level);
|
||||
|
||||
@@ -329,7 +335,7 @@ public:
|
||||
const std::string &name() const;
|
||||
|
||||
// set formatting for the sinks in this logger.
|
||||
// each sink will get a seperate instance of the formatter object.
|
||||
// each sink will get a separate instance of the formatter object.
|
||||
void set_formatter(std::unique_ptr<formatter> f);
|
||||
|
||||
void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local);
|
||||
@@ -364,6 +370,9 @@ protected:
|
||||
err_handler custom_err_handler_{nullptr};
|
||||
details::backtracer tracer_;
|
||||
|
||||
// log the given message (if the given log level is high enough),
|
||||
// and save backtrace (if backtrace is enabled).
|
||||
void log_it_(const details::log_msg &log_msg, bool log_enabled, bool traceback_enabled);
|
||||
virtual void sink_it_(const details::log_msg &msg);
|
||||
virtual void flush_();
|
||||
void dump_backtrace_();
|
||||
|
@@ -4,14 +4,14 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/details/pattern_formatter.h"
|
||||
#include <spdlog/pattern_formatter.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/details/fmt_helper.h"
|
||||
#include "spdlog/details/log_msg.h"
|
||||
#include "spdlog/details/os.h"
|
||||
#include "spdlog/fmt/fmt.h"
|
||||
#include "spdlog/formatter.h"
|
||||
#include <spdlog/details/fmt_helper.h>
|
||||
#include <spdlog/details/log_msg.h>
|
||||
#include <spdlog/details/os.h>
|
||||
#include <spdlog/fmt/fmt.h>
|
||||
#include <spdlog/formatter.h>
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
@@ -39,57 +39,70 @@ public:
|
||||
: padinfo_(padinfo)
|
||||
, dest_(dest)
|
||||
{
|
||||
|
||||
if (padinfo_.width_ <= wrapped_size)
|
||||
remaining_pad_ = static_cast<long>(padinfo.width_) - static_cast<long>(wrapped_size);
|
||||
if (remaining_pad_ <= 0)
|
||||
{
|
||||
total_pad_ = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
total_pad_ = padinfo.width_ - wrapped_size;
|
||||
if (padinfo_.side_ == padding_info::left)
|
||||
{
|
||||
pad_it(total_pad_);
|
||||
total_pad_ = 0;
|
||||
pad_it(remaining_pad_);
|
||||
remaining_pad_ = 0;
|
||||
}
|
||||
else if (padinfo_.side_ == padding_info::center)
|
||||
{
|
||||
auto half_pad = total_pad_ / 2;
|
||||
auto reminder = total_pad_ & 1;
|
||||
auto half_pad = remaining_pad_ / 2;
|
||||
auto reminder = remaining_pad_ & 1;
|
||||
pad_it(half_pad);
|
||||
total_pad_ = half_pad + reminder; // for the right side
|
||||
remaining_pad_ = half_pad + reminder; // for the right side
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
static unsigned int count_digits(T n)
|
||||
{
|
||||
return fmt_helper::count_digits(n);
|
||||
}
|
||||
|
||||
~scoped_padder()
|
||||
{
|
||||
if (total_pad_)
|
||||
if (remaining_pad_ >= 0)
|
||||
{
|
||||
pad_it(total_pad_);
|
||||
pad_it(remaining_pad_);
|
||||
}
|
||||
else if (padinfo_.truncate_)
|
||||
{
|
||||
long new_size = static_cast<long>(dest_.size()) + remaining_pad_;
|
||||
dest_.resize(static_cast<size_t>(new_size));
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
void pad_it(size_t count)
|
||||
void pad_it(long count)
|
||||
{
|
||||
// count = std::min(count, spaces_.size());
|
||||
assert(count <= spaces_.size());
|
||||
fmt_helper::append_string_view(string_view_t(spaces_.data(), count), dest_);
|
||||
fmt_helper::append_string_view(string_view_t(spaces_.data(), static_cast<size_t>(count)), dest_);
|
||||
}
|
||||
|
||||
const padding_info &padinfo_;
|
||||
memory_buf_t &dest_;
|
||||
size_t total_pad_;
|
||||
long remaining_pad_;
|
||||
string_view_t spaces_{" ", 64};
|
||||
};
|
||||
|
||||
struct null_scoped_padder
|
||||
{
|
||||
null_scoped_padder(size_t /*wrapped_size*/, const padding_info & /*padinfo*/, memory_buf_t & /*dest*/) {}
|
||||
|
||||
template<typename T>
|
||||
static unsigned int count_digits(T /* number */)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
template<typename ScopedPadder>
|
||||
class name_formatter : public flag_formatter
|
||||
class name_formatter final : public flag_formatter
|
||||
{
|
||||
public:
|
||||
explicit name_formatter(padding_info padinfo)
|
||||
@@ -105,7 +118,7 @@ public:
|
||||
|
||||
// log level appender
|
||||
template<typename ScopedPadder>
|
||||
class level_formatter : public flag_formatter
|
||||
class level_formatter final : public flag_formatter
|
||||
{
|
||||
public:
|
||||
explicit level_formatter(padding_info padinfo)
|
||||
@@ -122,7 +135,7 @@ public:
|
||||
|
||||
// short log level appender
|
||||
template<typename ScopedPadder>
|
||||
class short_level_formatter : public flag_formatter
|
||||
class short_level_formatter final : public flag_formatter
|
||||
{
|
||||
public:
|
||||
explicit short_level_formatter(padding_info padinfo)
|
||||
@@ -155,7 +168,7 @@ static int to12h(const tm &t)
|
||||
static std::array<const char *, 7> days{{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}};
|
||||
|
||||
template<typename ScopedPadder>
|
||||
class a_formatter : public flag_formatter
|
||||
class a_formatter final : public flag_formatter
|
||||
{
|
||||
public:
|
||||
explicit a_formatter(padding_info padinfo)
|
||||
@@ -193,7 +206,7 @@ public:
|
||||
static const std::array<const char *, 12> months{{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"}};
|
||||
|
||||
template<typename ScopedPadder>
|
||||
class b_formatter : public flag_formatter
|
||||
class b_formatter final : public flag_formatter
|
||||
{
|
||||
public:
|
||||
explicit b_formatter(padding_info padinfo)
|
||||
@@ -213,7 +226,7 @@ static const std::array<const char *, 12> full_months{
|
||||
{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}};
|
||||
|
||||
template<typename ScopedPadder>
|
||||
class B_formatter : public flag_formatter
|
||||
class B_formatter final : public flag_formatter
|
||||
{
|
||||
public:
|
||||
explicit B_formatter(padding_info padinfo)
|
||||
@@ -593,14 +606,7 @@ public:
|
||||
const size_t field_size = 6;
|
||||
ScopedPadder p(field_size, padinfo_, dest);
|
||||
|
||||
#ifdef _WIN32
|
||||
int total_minutes = get_cached_offset(msg, tm_time);
|
||||
#else
|
||||
// No need to chache under gcc,
|
||||
// it is very fast (already stored in tm.tm_gmtoff)
|
||||
(void)(msg);
|
||||
int total_minutes = os::utc_minutes_offset(tm_time);
|
||||
#endif
|
||||
auto total_minutes = get_cached_offset(msg, tm_time);
|
||||
bool is_negative = total_minutes < 0;
|
||||
if (is_negative)
|
||||
{
|
||||
@@ -619,7 +625,6 @@ public:
|
||||
|
||||
private:
|
||||
log_clock::time_point last_update_{std::chrono::seconds(0)};
|
||||
#ifdef _WIN32
|
||||
int offset_minutes_{0};
|
||||
|
||||
int get_cached_offset(const log_msg &msg, const std::tm &tm_time)
|
||||
@@ -632,7 +637,6 @@ private:
|
||||
}
|
||||
return offset_minutes_;
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
// Thread id
|
||||
@@ -646,7 +650,7 @@ public:
|
||||
|
||||
void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
|
||||
{
|
||||
const auto field_size = fmt_helper::count_digits(msg.thread_id);
|
||||
const auto field_size = ScopedPadder::count_digits(msg.thread_id);
|
||||
ScopedPadder p(field_size, padinfo_, dest);
|
||||
fmt_helper::append_int(msg.thread_id, dest);
|
||||
}
|
||||
@@ -664,7 +668,7 @@ public:
|
||||
void format(const details::log_msg &, const std::tm &, memory_buf_t &dest) override
|
||||
{
|
||||
const auto pid = static_cast<uint32_t>(details::os::pid());
|
||||
auto field_size = fmt_helper::count_digits(pid);
|
||||
auto field_size = ScopedPadder::count_digits(pid);
|
||||
ScopedPadder p(field_size, padinfo_, dest);
|
||||
fmt_helper::append_int(pid, dest);
|
||||
}
|
||||
@@ -763,8 +767,16 @@ public:
|
||||
return;
|
||||
}
|
||||
|
||||
size_t text_size =
|
||||
padinfo_.enabled() ? std::char_traits<char>::length(msg.source.filename) + fmt_helper::count_digits(msg.source.line) + 1 : 0;
|
||||
size_t text_size;
|
||||
if (padinfo_.enabled())
|
||||
{
|
||||
// calc text size for padding based on "filename:line"
|
||||
text_size = std::char_traits<char>::length(msg.source.filename) + ScopedPadder::count_digits(msg.source.line) + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
text_size = 0;
|
||||
}
|
||||
|
||||
ScopedPadder p(text_size, padinfo_, dest);
|
||||
fmt_helper::append_string_view(msg.source.filename, dest);
|
||||
@@ -836,7 +848,7 @@ public:
|
||||
return;
|
||||
}
|
||||
|
||||
auto field_size = fmt_helper::count_digits(msg.source.line);
|
||||
auto field_size = ScopedPadder::count_digits(msg.source.line);
|
||||
ScopedPadder p(field_size, padinfo_, dest);
|
||||
fmt_helper::append_int(msg.source.line, dest);
|
||||
}
|
||||
@@ -865,7 +877,6 @@ public:
|
||||
|
||||
// print elapsed time since last message
|
||||
template<typename ScopedPadder, typename Units>
|
||||
|
||||
class elapsed_formatter final : public flag_formatter
|
||||
{
|
||||
public:
|
||||
@@ -878,14 +889,16 @@ public:
|
||||
|
||||
void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
|
||||
{
|
||||
auto delta = std::max(msg.time - last_message_time_, log_clock::duration::zero());
|
||||
auto delta = (std::max)(msg.time - last_message_time_, log_clock::duration::zero());
|
||||
auto delta_units = std::chrono::duration_cast<DurationUnits>(delta);
|
||||
last_message_time_ = msg.time;
|
||||
ScopedPadder p(6, padinfo_, dest);
|
||||
fmt_helper::pad6(static_cast<size_t>(delta_units.count()), dest);
|
||||
auto delta_count = static_cast<size_t>(delta_units.count());
|
||||
auto n_digits = static_cast<size_t>(ScopedPadder::count_digits(delta_count));
|
||||
ScopedPadder p(n_digits, padinfo_, dest);
|
||||
fmt_helper::append_int(delta_count, dest);
|
||||
}
|
||||
|
||||
protected:
|
||||
private:
|
||||
log_clock::time_point last_message_time_;
|
||||
};
|
||||
|
||||
@@ -904,8 +917,6 @@ public:
|
||||
using std::chrono::milliseconds;
|
||||
using std::chrono::seconds;
|
||||
|
||||
#ifndef SPDLOG_NO_DATETIME
|
||||
|
||||
// cache the date/time part for the next second.
|
||||
auto duration = msg.time.time_since_epoch();
|
||||
auto secs = duration_cast<seconds>(duration);
|
||||
@@ -941,20 +952,15 @@ public:
|
||||
dest.push_back(']');
|
||||
dest.push_back(' ');
|
||||
|
||||
#else // no datetime needed
|
||||
(void)tm_time;
|
||||
#endif
|
||||
|
||||
#ifndef SPDLOG_NO_NAME
|
||||
// append logger name if exists
|
||||
if (msg.logger_name.size() > 0)
|
||||
{
|
||||
dest.push_back('[');
|
||||
// fmt_helper::append_str(*msg.logger_name, dest);
|
||||
fmt_helper::append_string_view(msg.logger_name, dest);
|
||||
dest.push_back(']');
|
||||
dest.push_back(' ');
|
||||
}
|
||||
#endif
|
||||
|
||||
dest.push_back('[');
|
||||
// wrap the level name with color
|
||||
msg.color_range_start = dest.size();
|
||||
@@ -986,11 +992,13 @@ private:
|
||||
|
||||
} // namespace details
|
||||
|
||||
SPDLOG_INLINE pattern_formatter::pattern_formatter(std::string pattern, pattern_time_type time_type, std::string eol)
|
||||
SPDLOG_INLINE pattern_formatter::pattern_formatter(
|
||||
std::string pattern, pattern_time_type time_type, std::string eol, custom_flags custom_user_flags)
|
||||
: pattern_(std::move(pattern))
|
||||
, eol_(std::move(eol))
|
||||
, pattern_time_type_(time_type)
|
||||
, last_log_secs_(0)
|
||||
, custom_handlers_(std::move(custom_user_flags))
|
||||
{
|
||||
std::memset(&cached_tm_, 0, sizeof(cached_tm_));
|
||||
compile_pattern_(pattern_);
|
||||
@@ -1009,19 +1017,23 @@ SPDLOG_INLINE pattern_formatter::pattern_formatter(pattern_time_type time_type,
|
||||
|
||||
SPDLOG_INLINE std::unique_ptr<formatter> pattern_formatter::clone() const
|
||||
{
|
||||
return details::make_unique<pattern_formatter>(pattern_, pattern_time_type_, eol_);
|
||||
custom_flags cloned_custom_formatters;
|
||||
for (auto &it : custom_handlers_)
|
||||
{
|
||||
cloned_custom_formatters[it.first] = it.second->clone();
|
||||
}
|
||||
return details::make_unique<pattern_formatter>(pattern_, pattern_time_type_, eol_, std::move(cloned_custom_formatters));
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void pattern_formatter::format(const details::log_msg &msg, memory_buf_t &dest)
|
||||
{
|
||||
#ifndef SPDLOG_NO_DATETIME
|
||||
auto secs = std::chrono::duration_cast<std::chrono::seconds>(msg.time.time_since_epoch());
|
||||
if (secs != last_log_secs_)
|
||||
{
|
||||
cached_tm_ = get_time_(msg);
|
||||
last_log_secs_ = secs;
|
||||
}
|
||||
#endif
|
||||
|
||||
for (auto &f : formatters_)
|
||||
{
|
||||
f->format(msg, cached_tm_, dest);
|
||||
@@ -1030,6 +1042,12 @@ SPDLOG_INLINE void pattern_formatter::format(const details::log_msg &msg, memory
|
||||
details::fmt_helper::append_string_view(eol_, dest);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void pattern_formatter::set_pattern(std::string pattern)
|
||||
{
|
||||
pattern_ = std::move(pattern);
|
||||
compile_pattern_(pattern_);
|
||||
}
|
||||
|
||||
SPDLOG_INLINE std::tm pattern_formatter::get_time_(const details::log_msg &msg)
|
||||
{
|
||||
if (pattern_time_type_ == pattern_time_type::local)
|
||||
@@ -1042,9 +1060,19 @@ SPDLOG_INLINE std::tm pattern_formatter::get_time_(const details::log_msg &msg)
|
||||
template<typename Padder>
|
||||
SPDLOG_INLINE void pattern_formatter::handle_flag_(char flag, details::padding_info padding)
|
||||
{
|
||||
// process custom flags
|
||||
auto it = custom_handlers_.find(flag);
|
||||
if (it != custom_handlers_.end())
|
||||
{
|
||||
auto custom_handler = it->second->clone();
|
||||
custom_handler->set_padding_info(padding);
|
||||
formatters_.push_back(std::move(custom_handler));
|
||||
return;
|
||||
}
|
||||
|
||||
// process built-in flags
|
||||
switch (flag)
|
||||
{
|
||||
|
||||
case ('+'): // default formatter
|
||||
formatters_.push_back(details::make_unique<details::full_formatter>(padding));
|
||||
break;
|
||||
@@ -1225,7 +1253,7 @@ SPDLOG_INLINE void pattern_formatter::handle_flag_(char flag, details::padding_i
|
||||
}
|
||||
}
|
||||
|
||||
// Extract given pad spec (e.g. %8X)
|
||||
// Extract given pad spec (e.g. %8X, %=8X, %-8!X, %8!X, %=8!X, %-8!X, %+8!X)
|
||||
// Advance the given it pass the end of the padding spec found (if any)
|
||||
// Return padding.
|
||||
SPDLOG_INLINE details::padding_info pattern_formatter::handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end)
|
||||
@@ -1256,7 +1284,7 @@ SPDLOG_INLINE details::padding_info pattern_formatter::handle_padspec_(std::stri
|
||||
|
||||
if (it == end || !std::isdigit(static_cast<unsigned char>(*it)))
|
||||
{
|
||||
return padding_info{0, side};
|
||||
return padding_info{}; // no padding if no digit found here
|
||||
}
|
||||
|
||||
auto width = static_cast<size_t>(*it) - '0';
|
||||
@@ -1265,7 +1293,20 @@ SPDLOG_INLINE details::padding_info pattern_formatter::handle_padspec_(std::stri
|
||||
auto digit = static_cast<size_t>(*it) - '0';
|
||||
width = width * 10 + digit;
|
||||
}
|
||||
return details::padding_info{std::min<size_t>(width, max_width), side};
|
||||
|
||||
// search for the optional truncate marker '!'
|
||||
bool truncate;
|
||||
if (it != end && *it == '!')
|
||||
{
|
||||
truncate = true;
|
||||
++it;
|
||||
}
|
||||
else
|
||||
{
|
||||
truncate = false;
|
||||
}
|
||||
|
||||
return details::padding_info{std::min<size_t>(width, max_width), side, truncate};
|
||||
}
|
||||
|
||||
SPDLOG_INLINE void pattern_formatter::compile_pattern_(const std::string &pattern)
|
@@ -3,10 +3,10 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/common.h"
|
||||
#include "spdlog/details/log_msg.h"
|
||||
#include "spdlog/details/os.h"
|
||||
#include "spdlog/formatter.h"
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/log_msg.h>
|
||||
#include <spdlog/details/os.h>
|
||||
#include <spdlog/formatter.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace spdlog {
|
||||
namespace details {
|
||||
@@ -29,20 +30,24 @@ struct padding_info
|
||||
};
|
||||
|
||||
padding_info() = default;
|
||||
padding_info(size_t width, padding_info::pad_side side)
|
||||
padding_info(size_t width, padding_info::pad_side side, bool truncate)
|
||||
: width_(width)
|
||||
, side_(side)
|
||||
, truncate_(truncate)
|
||||
, enabled_(true)
|
||||
{}
|
||||
|
||||
bool enabled() const
|
||||
{
|
||||
return width_ != 0;
|
||||
return enabled_;
|
||||
}
|
||||
const size_t width_ = 0;
|
||||
const pad_side side_ = left;
|
||||
size_t width_ = 0;
|
||||
pad_side side_ = left;
|
||||
bool truncate_ = false;
|
||||
bool enabled_ = false;
|
||||
};
|
||||
|
||||
class flag_formatter
|
||||
class SPDLOG_API flag_formatter
|
||||
{
|
||||
public:
|
||||
explicit flag_formatter(padding_info padinfo)
|
||||
@@ -58,11 +63,24 @@ protected:
|
||||
|
||||
} // namespace details
|
||||
|
||||
class pattern_formatter final : public formatter
|
||||
class SPDLOG_API custom_flag_formatter : public details::flag_formatter
|
||||
{
|
||||
public:
|
||||
explicit pattern_formatter(
|
||||
std::string pattern, pattern_time_type time_type = pattern_time_type::local, std::string eol = spdlog::details::os::default_eol);
|
||||
virtual std::unique_ptr<custom_flag_formatter> clone() const = 0;
|
||||
|
||||
void set_padding_info(details::padding_info padding)
|
||||
{
|
||||
flag_formatter::padinfo_ = padding;
|
||||
}
|
||||
};
|
||||
|
||||
class SPDLOG_API pattern_formatter final : public formatter
|
||||
{
|
||||
public:
|
||||
using custom_flags = std::unordered_map<char, std::unique_ptr<custom_flag_formatter>>;
|
||||
|
||||
explicit pattern_formatter(std::string pattern, pattern_time_type time_type = pattern_time_type::local,
|
||||
std::string eol = spdlog::details::os::default_eol, custom_flags custom_user_flags = custom_flags());
|
||||
|
||||
// use default pattern is not given
|
||||
explicit pattern_formatter(pattern_time_type time_type = pattern_time_type::local, std::string eol = spdlog::details::os::default_eol);
|
||||
@@ -73,6 +91,14 @@ public:
|
||||
std::unique_ptr<formatter> clone() const override;
|
||||
void format(const details::log_msg &msg, memory_buf_t &dest) override;
|
||||
|
||||
template<typename T, typename... Args>
|
||||
pattern_formatter &add_flag(char flag, const Args &... args)
|
||||
{
|
||||
custom_handlers_[flag] = details::make_unique<T>(args...);
|
||||
return *this;
|
||||
}
|
||||
void set_pattern(std::string pattern);
|
||||
|
||||
private:
|
||||
std::string pattern_;
|
||||
std::string eol_;
|
||||
@@ -80,6 +106,7 @@ private:
|
||||
std::tm cached_tm_;
|
||||
std::chrono::seconds last_log_secs_;
|
||||
std::vector<std::unique_ptr<details::flag_formatter>> formatters_;
|
||||
custom_flags custom_handlers_;
|
||||
|
||||
std::tm get_time_(const details::log_msg &msg);
|
||||
template<typename Padder>
|
||||
@@ -88,7 +115,7 @@ private:
|
||||
// Extract given pad spec (e.g. %8X)
|
||||
// Advance the given it pass the end of the padding spec found (if any)
|
||||
// Return padding.
|
||||
details::padding_info handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end);
|
||||
static details::padding_info handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end);
|
||||
|
||||
void compile_pattern_(const std::string &pattern);
|
||||
};
|
@@ -5,11 +5,11 @@
|
||||
|
||||
#ifdef __ANDROID__
|
||||
|
||||
#include "spdlog/details/fmt_helper.h"
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
#include "spdlog/details/os.h"
|
||||
#include "spdlog/sinks/base_sink.h"
|
||||
#include "spdlog/details/synchronous_factory.h"
|
||||
#include <spdlog/details/fmt_helper.h>
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <spdlog/details/os.h>
|
||||
#include <spdlog/sinks/base_sink.h>
|
||||
#include <spdlog/details/synchronous_factory.h>
|
||||
|
||||
#include <android/log.h>
|
||||
#include <chrono>
|
||||
@@ -64,7 +64,7 @@ protected:
|
||||
|
||||
if (ret < 0)
|
||||
{
|
||||
SPDLOG_THROW(spdlog_ex("__android_log_write() failed", ret));
|
||||
throw_spdlog_ex("__android_log_write() failed", ret);
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -4,11 +4,11 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/sinks/ansicolor_sink.h"
|
||||
#include <spdlog/sinks/ansicolor_sink.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/details/pattern_formatter.h"
|
||||
#include "spdlog/details/os.h"
|
||||
#include <spdlog/pattern_formatter.h>
|
||||
#include <spdlog/details/os.h>
|
||||
|
||||
namespace spdlog {
|
||||
namespace sinks {
|
||||
@@ -21,20 +21,20 @@ SPDLOG_INLINE ansicolor_sink<ConsoleMutex>::ansicolor_sink(FILE *target_file, co
|
||||
|
||||
{
|
||||
set_color_mode(mode);
|
||||
colors_[level::trace] = white;
|
||||
colors_[level::debug] = cyan;
|
||||
colors_[level::info] = green;
|
||||
colors_[level::warn] = yellow_bold;
|
||||
colors_[level::err] = red_bold;
|
||||
colors_[level::critical] = bold_on_red;
|
||||
colors_[level::off] = reset;
|
||||
colors_[level::trace] = to_string_(white);
|
||||
colors_[level::debug] = to_string_(cyan);
|
||||
colors_[level::info] = to_string_(green);
|
||||
colors_[level::warn] = to_string_(yellow_bold);
|
||||
colors_[level::err] = to_string_(red_bold);
|
||||
colors_[level::critical] = to_string_(bold_on_red);
|
||||
colors_[level::off] = to_string_(reset);
|
||||
}
|
||||
|
||||
template<typename ConsoleMutex>
|
||||
SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::set_color(level::level_enum color_level, string_view_t color)
|
||||
{
|
||||
std::lock_guard<mutex_t> lock(mutex_);
|
||||
colors_[color_level] = color;
|
||||
colors_[color_level] = to_string_(color);
|
||||
}
|
||||
|
||||
template<typename ConsoleMutex>
|
||||
@@ -43,7 +43,8 @@ SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::log(const details::log_msg &msg
|
||||
// Wrap the originally formatted message in color codes.
|
||||
// If color is not supported in the terminal, log as is instead.
|
||||
std::lock_guard<mutex_t> lock(mutex_);
|
||||
|
||||
msg.color_range_start = 0;
|
||||
msg.color_range_end = 0;
|
||||
memory_buf_t formatted;
|
||||
formatter_->format(msg, formatted);
|
||||
if (should_do_colors_ && msg.color_range_end > msg.color_range_start)
|
||||
@@ -111,7 +112,7 @@ SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::set_color_mode(color_mode mode)
|
||||
template<typename ConsoleMutex>
|
||||
SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::print_ccode_(const string_view_t &color_code)
|
||||
{
|
||||
fwrite(color_code.data(), sizeof(string_view_t::char_type), color_code.size(), target_file_);
|
||||
fwrite(color_code.data(), sizeof(char), color_code.size(), target_file_);
|
||||
}
|
||||
|
||||
template<typename ConsoleMutex>
|
||||
@@ -120,6 +121,12 @@ SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::print_range_(const memory_buf_t
|
||||
fwrite(formatted.data() + start, sizeof(char), end - start, target_file_);
|
||||
}
|
||||
|
||||
template<typename ConsoleMutex>
|
||||
SPDLOG_INLINE std::string ansicolor_sink<ConsoleMutex>::to_string_(const string_view_t &sv)
|
||||
{
|
||||
return std::string(sv.data(), sv.size());
|
||||
}
|
||||
|
||||
// ansicolor_stdout_sink
|
||||
template<typename ConsoleMutex>
|
||||
SPDLOG_INLINE ansicolor_stdout_sink<ConsoleMutex>::ansicolor_stdout_sink(color_mode mode)
|
||||
|
@@ -3,13 +3,13 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/details/console_globals.h"
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
#include "spdlog/sinks/sink.h"
|
||||
#include <spdlog/details/console_globals.h>
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <spdlog/sinks/sink.h>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <array>
|
||||
|
||||
namespace spdlog {
|
||||
namespace sinks {
|
||||
@@ -30,7 +30,11 @@ public:
|
||||
~ansicolor_sink() override = default;
|
||||
|
||||
ansicolor_sink(const ansicolor_sink &other) = delete;
|
||||
ansicolor_sink(ansicolor_sink &&other) = delete;
|
||||
|
||||
ansicolor_sink &operator=(const ansicolor_sink &other) = delete;
|
||||
ansicolor_sink &operator=(ansicolor_sink &&other) = delete;
|
||||
|
||||
void set_color(level::level_enum color_level, string_view_t color);
|
||||
void set_color_mode(color_mode mode);
|
||||
bool should_color();
|
||||
@@ -80,9 +84,10 @@ private:
|
||||
mutex_t &mutex_;
|
||||
bool should_do_colors_;
|
||||
std::unique_ptr<spdlog::formatter> formatter_;
|
||||
std::unordered_map<level::level_enum, string_view_t, level::level_hasher> colors_;
|
||||
std::array<std::string, level::n_levels> colors_;
|
||||
void print_ccode_(const string_view_t &color_code);
|
||||
void print_range_(const memory_buf_t &formatted, size_t start, size_t end);
|
||||
static std::string to_string_(const string_view_t &sv);
|
||||
};
|
||||
|
||||
template<typename ConsoleMutex>
|
||||
|
@@ -4,11 +4,11 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/sinks/base_sink.h"
|
||||
#include <spdlog/sinks/base_sink.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/common.h"
|
||||
#include "spdlog/details/pattern_formatter.h"
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/pattern_formatter.h>
|
||||
|
||||
#include <memory>
|
||||
|
||||
|
@@ -9,9 +9,9 @@
|
||||
// implementers..
|
||||
//
|
||||
|
||||
#include "spdlog/common.h"
|
||||
#include "spdlog/details/log_msg.h"
|
||||
#include "spdlog/sinks/sink.h"
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/log_msg.h>
|
||||
#include <spdlog/sinks/sink.h>
|
||||
|
||||
namespace spdlog {
|
||||
namespace sinks {
|
||||
@@ -21,8 +21,14 @@ class base_sink : public sink
|
||||
public:
|
||||
base_sink();
|
||||
explicit base_sink(std::unique_ptr<spdlog::formatter> formatter);
|
||||
~base_sink() override = default;
|
||||
|
||||
base_sink(const base_sink &) = delete;
|
||||
base_sink(base_sink &&) = delete;
|
||||
|
||||
base_sink &operator=(const base_sink &) = delete;
|
||||
base_sink &operator=(base_sink &&) = delete;
|
||||
|
||||
void log(const details::log_msg &msg) final;
|
||||
void flush() final;
|
||||
void set_pattern(const std::string &pattern) final;
|
||||
|
@@ -4,11 +4,11 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/sinks/basic_file_sink.h"
|
||||
#include <spdlog/sinks/basic_file_sink.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/common.h"
|
||||
#include "spdlog/details/os.h"
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/os.h>
|
||||
|
||||
namespace spdlog {
|
||||
namespace sinks {
|
||||
|
@@ -3,10 +3,10 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/details/file_helper.h"
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
#include "spdlog/sinks/base_sink.h"
|
||||
#include "spdlog/details/synchronous_factory.h"
|
||||
#include <spdlog/details/file_helper.h>
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <spdlog/sinks/base_sink.h>
|
||||
#include <spdlog/details/synchronous_factory.h>
|
||||
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
@@ -3,13 +3,14 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/common.h"
|
||||
#include "spdlog/details/file_helper.h"
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
#include "spdlog/fmt/fmt.h"
|
||||
#include "spdlog/sinks/base_sink.h"
|
||||
#include "spdlog/details/os.h"
|
||||
#include "spdlog/details/synchronous_factory.h"
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/details/file_helper.h>
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <spdlog/fmt/fmt.h>
|
||||
#include <spdlog/sinks/base_sink.h>
|
||||
#include <spdlog/details/os.h>
|
||||
#include <spdlog/details/circular_q.h>
|
||||
#include <spdlog/details/synchronous_factory.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
@@ -55,7 +56,7 @@ public:
|
||||
{
|
||||
if (rotation_hour < 0 || rotation_hour > 23 || rotation_minute < 0 || rotation_minute > 59)
|
||||
{
|
||||
SPDLOG_THROW(spdlog_ex("daily_file_sink: Invalid rotation time in ctor"));
|
||||
throw_spdlog_ex("daily_file_sink: Invalid rotation time in ctor");
|
||||
}
|
||||
|
||||
auto now = log_clock::now();
|
||||
@@ -65,25 +66,20 @@ public:
|
||||
|
||||
if (max_files_ > 0)
|
||||
{
|
||||
filenames_q_ = details::circular_q<filename_t>(static_cast<size_t>(max_files_));
|
||||
filenames_q_.push_back(std::move(filename));
|
||||
init_filenames_q_();
|
||||
}
|
||||
}
|
||||
|
||||
const filename_t &filename() const
|
||||
filename_t filename()
|
||||
{
|
||||
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
|
||||
return file_helper_.filename();
|
||||
}
|
||||
|
||||
protected:
|
||||
void sink_it_(const details::log_msg &msg) override
|
||||
{
|
||||
#ifdef SPDLOG_NO_DATETIME
|
||||
auto time = log_clock::now();
|
||||
#else
|
||||
auto time = msg.time;
|
||||
#endif
|
||||
|
||||
bool should_rotate = time >= rotation_tp_;
|
||||
if (should_rotate)
|
||||
{
|
||||
@@ -95,7 +91,7 @@ protected:
|
||||
base_sink<Mutex>::formatter_->format(msg, formatted);
|
||||
file_helper_.write(formatted);
|
||||
|
||||
// Do the cleaning ony at the end because it might throw on failure.
|
||||
// Do the cleaning only at the end because it might throw on failure.
|
||||
if (should_rotate && max_files_ > 0)
|
||||
{
|
||||
delete_old_();
|
||||
@@ -108,6 +104,29 @@ protected:
|
||||
}
|
||||
|
||||
private:
|
||||
void init_filenames_q_()
|
||||
{
|
||||
using details::os::path_exists;
|
||||
|
||||
filenames_q_ = details::circular_q<filename_t>(static_cast<size_t>(max_files_));
|
||||
std::vector<filename_t> filenames;
|
||||
auto now = log_clock::now();
|
||||
while (filenames.size() < max_files_)
|
||||
{
|
||||
auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
|
||||
if (!path_exists(filename))
|
||||
{
|
||||
break;
|
||||
}
|
||||
filenames.emplace_back(filename);
|
||||
now -= std::chrono::hours(24);
|
||||
}
|
||||
for (auto iter = filenames.rbegin(); iter != filenames.rend(); ++iter)
|
||||
{
|
||||
filenames_q_.push_back(std::move(*iter));
|
||||
}
|
||||
}
|
||||
|
||||
tm now_tm(log_clock::time_point tp)
|
||||
{
|
||||
time_t tnow = log_clock::to_time_t(tp);
|
||||
@@ -136,7 +155,7 @@ private:
|
||||
using details::os::filename_to_str;
|
||||
using details::os::remove_if_exists;
|
||||
|
||||
filename_t current_file = filename();
|
||||
filename_t current_file = file_helper_.filename();
|
||||
if (filenames_q_.full())
|
||||
{
|
||||
auto old_filename = std::move(filenames_q_.front());
|
||||
@@ -145,7 +164,7 @@ private:
|
||||
if (!ok)
|
||||
{
|
||||
filenames_q_.push_back(std::move(current_file));
|
||||
SPDLOG_THROW(spdlog_ex("Failed removing daily file " + filename_to_str(old_filename), errno));
|
||||
throw_spdlog_ex("Failed removing daily file " + filename_to_str(old_filename), errno);
|
||||
}
|
||||
}
|
||||
filenames_q_.push_back(std::move(current_file));
|
||||
@@ -171,15 +190,15 @@ using daily_file_sink_st = daily_file_sink<details::null_mutex>;
|
||||
//
|
||||
template<typename Factory = spdlog::synchronous_factory>
|
||||
inline std::shared_ptr<logger> daily_logger_mt(
|
||||
const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false)
|
||||
const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0)
|
||||
{
|
||||
return Factory::template create<sinks::daily_file_sink_mt>(logger_name, filename, hour, minute, truncate);
|
||||
return Factory::template create<sinks::daily_file_sink_mt>(logger_name, filename, hour, minute, truncate, max_files);
|
||||
}
|
||||
|
||||
template<typename Factory = spdlog::synchronous_factory>
|
||||
inline std::shared_ptr<logger> daily_logger_st(
|
||||
const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false)
|
||||
const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0)
|
||||
{
|
||||
return Factory::template create<sinks::daily_file_sink_st>(logger_name, filename, hour, minute, truncate);
|
||||
return Factory::template create<sinks::daily_file_sink_st>(logger_name, filename, hour, minute, truncate, max_files);
|
||||
}
|
||||
} // namespace spdlog
|
||||
|
@@ -4,9 +4,9 @@
|
||||
#pragma once
|
||||
|
||||
#include "base_sink.h"
|
||||
#include "spdlog/details/log_msg.h"
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
#include "spdlog/details/pattern_formatter.h"
|
||||
#include <spdlog/details/log_msg.h>
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <spdlog/pattern_formatter.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
@@ -24,6 +24,10 @@ class dist_sink : public base_sink<Mutex>
|
||||
{
|
||||
public:
|
||||
dist_sink() = default;
|
||||
explicit dist_sink(std::vector<std::shared_ptr<sink>> sinks)
|
||||
: sinks_(sinks)
|
||||
{}
|
||||
|
||||
dist_sink(const dist_sink &) = delete;
|
||||
dist_sink &operator=(const dist_sink &) = delete;
|
||||
|
||||
|
@@ -4,8 +4,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "dist_sink.h"
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
#include "spdlog/details/log_msg.h"
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <spdlog/details/log_msg.h>
|
||||
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
@@ -16,7 +16,7 @@
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// #include "spdlog/sinks/dup_filter_sink.h"
|
||||
// #include <spdlog/sinks/dup_filter_sink.h>
|
||||
//
|
||||
// int main() {
|
||||
// auto dup_filter = std::make_shared<dup_filter_sink_st>(std::chrono::seconds(5));
|
||||
@@ -33,10 +33,6 @@
|
||||
// [2019-06-25 17:50:56.512] [logger] [info] Skipped 3 duplicate messages..
|
||||
// [2019-06-25 17:50:56.512] [logger] [info] Different Hello
|
||||
|
||||
#ifdef SPDLOG_NO_DATETIME
|
||||
#error "spdlog::sinks::dup_filter_sink: cannot work when SPDLOG_NO_DATETIME is defined"
|
||||
#endif
|
||||
|
||||
namespace spdlog {
|
||||
namespace sinks {
|
||||
template<typename Mutex>
|
||||
|
@@ -5,9 +5,10 @@
|
||||
|
||||
#if defined(_WIN32)
|
||||
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
#include "spdlog/sinks/base_sink.h"
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <spdlog/sinks/base_sink.h>
|
||||
|
||||
#include <spdlog/details/windows_include.h>
|
||||
#include <winbase.h>
|
||||
|
||||
#include <mutex>
|
||||
|
@@ -3,9 +3,9 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
#include "spdlog/sinks/base_sink.h"
|
||||
#include "spdlog/details/synchronous_factory.h"
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <spdlog/sinks/base_sink.h>
|
||||
#include <spdlog/details/synchronous_factory.h>
|
||||
|
||||
#include <mutex>
|
||||
|
||||
|
@@ -3,8 +3,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
#include "spdlog/sinks/base_sink.h"
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <spdlog/sinks/base_sink.h>
|
||||
|
||||
#include <mutex>
|
||||
#include <ostream>
|
||||
|
74
include/spdlog/sinks/ringbuffer_sink.h
Normal file
74
include/spdlog/sinks/ringbuffer_sink.h
Normal file
@@ -0,0 +1,74 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/sinks/base_sink.h"
|
||||
#include "spdlog/details/circular_q.h"
|
||||
#include "spdlog/details/log_msg_buffer.h"
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace spdlog {
|
||||
namespace sinks {
|
||||
/*
|
||||
* Ring buffer sink
|
||||
*/
|
||||
template<typename Mutex>
|
||||
class ringbuffer_sink final : public base_sink<Mutex>
|
||||
{
|
||||
public:
|
||||
explicit ringbuffer_sink(size_t n_items)
|
||||
: q_{n_items}
|
||||
{}
|
||||
|
||||
std::vector<details::log_msg_buffer> last_raw(size_t lim = 0)
|
||||
{
|
||||
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
|
||||
auto items_available = q_.size();
|
||||
auto n_items = lim > 0 ? (std::min)(lim, items_available) : items_available;
|
||||
std::vector<details::log_msg_buffer> ret;
|
||||
ret.reserve(n_items);
|
||||
for (size_t i = (items_available - n_items); i < items_available; i++)
|
||||
{
|
||||
ret.push_back(q_.at(i));
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
std::vector<std::string> last_formatted(size_t lim = 0)
|
||||
{
|
||||
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
|
||||
auto items_available = q_.size();
|
||||
auto n_items = lim > 0 ? (std::min)(lim, items_available) : items_available;
|
||||
std::vector<std::string> ret;
|
||||
ret.reserve(n_items);
|
||||
for (size_t i = (items_available - n_items); i < items_available; i++)
|
||||
{
|
||||
memory_buf_t formatted;
|
||||
base_sink<Mutex>::formatter_->format(q_.at(i), formatted);
|
||||
ret.push_back(fmt::to_string(formatted));
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
protected:
|
||||
void sink_it_(const details::log_msg &msg) override
|
||||
{
|
||||
q_.push_back(details::log_msg_buffer{msg});
|
||||
}
|
||||
void flush_() override {}
|
||||
|
||||
private:
|
||||
details::circular_q<details::log_msg_buffer> q_;
|
||||
};
|
||||
|
||||
using ringbuffer_sink_mt = ringbuffer_sink<std::mutex>;
|
||||
using ringbuffer_sink_st = ringbuffer_sink<details::null_mutex>;
|
||||
|
||||
} // namespace sinks
|
||||
|
||||
} // namespace spdlog
|
@@ -4,14 +4,14 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/sinks/rotating_file_sink.h"
|
||||
#include <spdlog/sinks/rotating_file_sink.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/common.h"
|
||||
#include <spdlog/common.h>
|
||||
|
||||
#include "spdlog/details/file_helper.h"
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
#include "spdlog/fmt/fmt.h"
|
||||
#include <spdlog/details/file_helper.h>
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <spdlog/fmt/fmt.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
@@ -54,8 +54,9 @@ SPDLOG_INLINE filename_t rotating_file_sink<Mutex>::calc_filename(const filename
|
||||
}
|
||||
|
||||
template<typename Mutex>
|
||||
SPDLOG_INLINE const filename_t &rotating_file_sink<Mutex>::filename() const
|
||||
SPDLOG_INLINE filename_t rotating_file_sink<Mutex>::filename()
|
||||
{
|
||||
std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
|
||||
return file_helper_.filename();
|
||||
}
|
||||
|
||||
@@ -88,28 +89,28 @@ template<typename Mutex>
|
||||
SPDLOG_INLINE void rotating_file_sink<Mutex>::rotate_()
|
||||
{
|
||||
using details::os::filename_to_str;
|
||||
using details::os::path_exists;
|
||||
file_helper_.close();
|
||||
for (auto i = max_files_; i > 0; --i)
|
||||
{
|
||||
filename_t src = calc_filename(base_filename_, i - 1);
|
||||
if (!details::file_helper::file_exists(src))
|
||||
if (!path_exists(src))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
filename_t target = calc_filename(base_filename_, i);
|
||||
|
||||
if (!rename_file(src, target))
|
||||
if (!rename_file_(src, target))
|
||||
{
|
||||
// if failed try again after a small delay.
|
||||
// this is a workaround to a windows issue, where very high rotation
|
||||
// rates can cause the rename to fail with permission denied (because of antivirus?).
|
||||
details::os::sleep_for_millis(100);
|
||||
if (!rename_file(src, target))
|
||||
if (!rename_file_(src, target))
|
||||
{
|
||||
file_helper_.reopen(true); // truncate the log file anyway to prevent it to grow beyond its limit!
|
||||
current_size_ = 0;
|
||||
SPDLOG_THROW(
|
||||
spdlog_ex("rotating_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target), errno));
|
||||
throw_spdlog_ex("rotating_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target), errno);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -119,7 +120,7 @@ SPDLOG_INLINE void rotating_file_sink<Mutex>::rotate_()
|
||||
// delete the target if exists, and rename the src file to target
|
||||
// return true on success, false otherwise.
|
||||
template<typename Mutex>
|
||||
SPDLOG_INLINE bool rotating_file_sink<Mutex>::rename_file(const filename_t &src_filename, const filename_t &target_filename)
|
||||
SPDLOG_INLINE bool rotating_file_sink<Mutex>::rename_file_(const filename_t &src_filename, const filename_t &target_filename)
|
||||
{
|
||||
// try to delete the target file in case it already exists.
|
||||
(void)details::os::remove(target_filename);
|
||||
|
@@ -3,10 +3,10 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/sinks/base_sink.h"
|
||||
#include "spdlog/details/file_helper.h"
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
#include "spdlog/details/synchronous_factory.h"
|
||||
#include <spdlog/sinks/base_sink.h>
|
||||
#include <spdlog/details/file_helper.h>
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <spdlog/details/synchronous_factory.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
@@ -24,7 +24,7 @@ class rotating_file_sink final : public base_sink<Mutex>
|
||||
public:
|
||||
rotating_file_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files, bool rotate_on_open = false);
|
||||
static filename_t calc_filename(const filename_t &filename, std::size_t index);
|
||||
const filename_t &filename() const;
|
||||
filename_t filename();
|
||||
|
||||
protected:
|
||||
void sink_it_(const details::log_msg &msg) override;
|
||||
@@ -40,7 +40,7 @@ private:
|
||||
|
||||
// delete the target if exists, and rename the src file to target
|
||||
// return true on success, false otherwise.
|
||||
bool rename_file(const filename_t &src_filename, const filename_t &target_filename);
|
||||
bool rename_file_(const filename_t &src_filename, const filename_t &target_filename);
|
||||
|
||||
filename_t base_filename_;
|
||||
std::size_t max_size_;
|
||||
@@ -75,4 +75,4 @@ inline std::shared_ptr<logger> rotating_logger_st(
|
||||
|
||||
#ifdef SPDLOG_HEADER_ONLY
|
||||
#include "rotating_file_sink-inl.h"
|
||||
#endif
|
||||
#endif
|
||||
|
@@ -4,10 +4,10 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/sinks/sink.h"
|
||||
#include <spdlog/sinks/sink.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/common.h"
|
||||
#include <spdlog/common.h>
|
||||
|
||||
SPDLOG_INLINE bool spdlog::sinks::sink::should_log(spdlog::level::level_enum msg_level) const
|
||||
{
|
||||
|
@@ -3,13 +3,13 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/details/log_msg.h"
|
||||
#include "spdlog/formatter.h"
|
||||
#include <spdlog/details/log_msg.h>
|
||||
#include <spdlog/formatter.h>
|
||||
|
||||
namespace spdlog {
|
||||
|
||||
namespace sinks {
|
||||
class sink
|
||||
class SPDLOG_API sink
|
||||
{
|
||||
public:
|
||||
virtual ~sink() = default;
|
||||
|
@@ -4,11 +4,11 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/sinks/stdout_color_sinks.h"
|
||||
#include <spdlog/sinks/stdout_color_sinks.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/logger.h"
|
||||
#include "spdlog/common.h"
|
||||
#include <spdlog/logger.h>
|
||||
#include <spdlog/common.h>
|
||||
|
||||
namespace spdlog {
|
||||
|
||||
|
@@ -4,12 +4,12 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef _WIN32
|
||||
#include "spdlog/sinks/wincolor_sink.h"
|
||||
#include <spdlog/sinks/wincolor_sink.h>
|
||||
#else
|
||||
#include "spdlog/sinks/ansicolor_sink.h"
|
||||
#include <spdlog/sinks/ansicolor_sink.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/details/synchronous_factory.h"
|
||||
#include <spdlog/details/synchronous_factory.h>
|
||||
|
||||
namespace spdlog {
|
||||
namespace sinks {
|
||||
|
@@ -4,11 +4,11 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SPDLOG_HEADER_ONLY
|
||||
#include "spdlog/sinks/stdout_sinks.h"
|
||||
#include <spdlog/sinks/stdout_sinks.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/details/console_globals.h"
|
||||
#include "spdlog/details/pattern_formatter.h"
|
||||
#include <spdlog/details/console_globals.h>
|
||||
#include <spdlog/pattern_formatter.h>
|
||||
#include <memory>
|
||||
|
||||
namespace spdlog {
|
||||
|
@@ -3,9 +3,9 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/details/console_globals.h"
|
||||
#include "spdlog/details/synchronous_factory.h"
|
||||
#include "spdlog/sinks/sink.h"
|
||||
#include <spdlog/details/console_globals.h>
|
||||
#include <spdlog/details/synchronous_factory.h>
|
||||
#include <spdlog/sinks/sink.h>
|
||||
#include <cstdio>
|
||||
|
||||
namespace spdlog {
|
||||
@@ -19,8 +19,12 @@ public:
|
||||
using mutex_t = typename ConsoleMutex::mutex_t;
|
||||
explicit stdout_sink_base(FILE *file);
|
||||
~stdout_sink_base() override = default;
|
||||
|
||||
stdout_sink_base(const stdout_sink_base &other) = delete;
|
||||
stdout_sink_base(stdout_sink_base &&other) = delete;
|
||||
|
||||
stdout_sink_base &operator=(const stdout_sink_base &other) = delete;
|
||||
stdout_sink_base &operator=(stdout_sink_base &&other) = delete;
|
||||
|
||||
void log(const details::log_msg &msg) override;
|
||||
void flush() override;
|
||||
|
@@ -3,8 +3,9 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/sinks/base_sink.h"
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
#include <spdlog/sinks/base_sink.h>
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <spdlog/details/synchronous_factory.h>
|
||||
|
||||
#include <array>
|
||||
#include <string>
|
||||
@@ -92,14 +93,14 @@ using syslog_sink_st = syslog_sink<details::null_mutex>;
|
||||
} // namespace sinks
|
||||
|
||||
// Create and register a syslog logger
|
||||
template<typename Factory = default_factory>
|
||||
template<typename Factory = spdlog::synchronous_factory>
|
||||
inline std::shared_ptr<logger> syslog_logger_mt(const std::string &logger_name, const std::string &syslog_ident = "", int syslog_option = 0,
|
||||
int syslog_facility = LOG_USER, bool enable_formatting = false)
|
||||
{
|
||||
return Factory::template create<sinks::syslog_sink_mt>(logger_name, syslog_ident, syslog_option, syslog_facility, enable_formatting);
|
||||
}
|
||||
|
||||
template<typename Factory = default_factory>
|
||||
template<typename Factory = spdlog::synchronous_factory>
|
||||
inline std::shared_ptr<logger> syslog_logger_st(const std::string &logger_name, const std::string &syslog_ident = "", int syslog_option = 0,
|
||||
int syslog_facility = LOG_USER, bool enable_formatting = false)
|
||||
{
|
||||
|
@@ -3,10 +3,14 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "spdlog/sinks/base_sink.h"
|
||||
#include "spdlog/details/null_mutex.h"
|
||||
#include "spdlog/details/synchronous_factory.h"
|
||||
#include <spdlog/sinks/base_sink.h>
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#include <spdlog/details/synchronous_factory.h>
|
||||
|
||||
#include <array>
|
||||
#ifndef SD_JOURNAL_SUPPRESS_LOCATION
|
||||
#define SD_JOURNAL_SUPPRESS_LOCATION
|
||||
#endif
|
||||
#include <systemd/sd-journal.h>
|
||||
|
||||
namespace spdlog {
|
||||
@@ -56,18 +60,19 @@ protected:
|
||||
if (msg.source.empty())
|
||||
{
|
||||
// Note: function call inside '()' to avoid macro expansion
|
||||
err = (sd_journal_send)(
|
||||
"MESSAGE=%.*s", static_cast<int>(length), msg.payload.data(), "PRIORITY=%d", syslog_level(msg.level), nullptr);
|
||||
err = (sd_journal_send)("MESSAGE=%.*s", static_cast<int>(length), msg.payload.data(), "PRIORITY=%d", syslog_level(msg.level),
|
||||
"SYSLOG_IDENTIFIER=%.*s", static_cast<int>(msg.logger_name.size()), msg.logger_name.data(), nullptr);
|
||||
}
|
||||
else
|
||||
{
|
||||
err = (sd_journal_send)("MESSAGE=%.*s", static_cast<int>(length), msg.payload.data(), "PRIORITY=%d", syslog_level(msg.level),
|
||||
"SOURCE_FILE=%s", msg.source.filename, "SOURCE_LINE=%d", msg.source.line, "SOURCE_FUNC=%s", msg.source.funcname, nullptr);
|
||||
"SYSLOG_IDENTIFIER=%.*s", static_cast<int>(msg.logger_name.size()), msg.logger_name.data(), "CODE_FILE=%s",
|
||||
msg.source.filename, "CODE_LINE=%d", msg.source.line, "CODE_FUNC=%s", msg.source.funcname, nullptr);
|
||||
}
|
||||
|
||||
if (err)
|
||||
{
|
||||
SPDLOG_THROW(spdlog_ex("Failed writing to systemd", errno));
|
||||
throw_spdlog_ex("Failed writing to systemd", errno);
|
||||
}
|
||||
}
|
||||
|
||||
|
81
include/spdlog/sinks/tcp_sink.h
Normal file
81
include/spdlog/sinks/tcp_sink.h
Normal file
@@ -0,0 +1,81 @@
|
||||
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/sinks/base_sink.h>
|
||||
#include <spdlog/details/null_mutex.h>
|
||||
#ifdef _WIN32
|
||||
#include <spdlog/details/tcp_client-windows.h>
|
||||
#else
|
||||
#include <spdlog/details/tcp_client.h>
|
||||
#endif
|
||||
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
|
||||
#pragma once
|
||||
|
||||
// Simple tcp client sink
|
||||
// Connects to remote address and send the formatted log.
|
||||
// Will attempt to reconnect if connection drops.
|
||||
// If more complicated behaviour is needed (i.e get responses), you can inherit it and override the sink_it_ method.
|
||||
|
||||
namespace spdlog {
|
||||
namespace sinks {
|
||||
|
||||
struct tcp_sink_config
|
||||
{
|
||||
std::string server_host;
|
||||
int server_port;
|
||||
bool lazy_connect = false; // if true connect on first log call instead of on construction
|
||||
|
||||
tcp_sink_config(std::string host, int port)
|
||||
: server_host{std::move(host)}
|
||||
, server_port{port}
|
||||
{}
|
||||
};
|
||||
|
||||
template<typename Mutex>
|
||||
class tcp_sink : public spdlog::sinks::base_sink<Mutex>
|
||||
{
|
||||
public:
|
||||
// connect to tcp host/port or throw if failed
|
||||
// host can be hostname or ip address
|
||||
|
||||
explicit tcp_sink(tcp_sink_config sink_config)
|
||||
: config_{std::move(sink_config)}
|
||||
{
|
||||
if (!config_.lazy_connect)
|
||||
{
|
||||
this->client_.connect(config_.server_host, config_.server_port);
|
||||
}
|
||||
}
|
||||
|
||||
~tcp_sink() override = default;
|
||||
|
||||
protected:
|
||||
void sink_it_(const spdlog::details::log_msg &msg) override
|
||||
{
|
||||
spdlog::memory_buf_t formatted;
|
||||
spdlog::sinks::base_sink<Mutex>::formatter_->format(msg, formatted);
|
||||
if (!client_.is_connected())
|
||||
{
|
||||
client_.connect(config_.server_host, config_.server_port);
|
||||
}
|
||||
client_.send(formatted.data(), formatted.size());
|
||||
}
|
||||
|
||||
void flush_() override {}
|
||||
tcp_sink_config config_;
|
||||
details::tcp_client client_;
|
||||
};
|
||||
|
||||
using tcp_sink_mt = tcp_sink<std::mutex>;
|
||||
using tcp_sink_st = tcp_sink<spdlog::details::null_mutex>;
|
||||
|
||||
} // namespace sinks
|
||||
} // namespace spdlog
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user