nolog 1.0.19

Pretty (by default) and easy to use logger. Compile-time level filtering, zero deps.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
# nolog logger

Convenient and 'beautiful by default' logger for debugging your programs.
Easy to use, complete documentation is provided on this page. Zero deps.
No unsafe (by `#![deny(unsafe_code)]`).

![nolog](https://raw.githubusercontent.com/vglinka/nolog/main/assets/term.gif)

<p align="center">
<a href="https://github.com/vglinka/nolog/blob/main/examples/novus/main.rs" target="_blank">See this example code</a>
</p>

## nolog features
- In most cases `nolog` uses a `std::format_args!()` (that avoids heap
  allocations) and compile-time level filtering by Cargo features.
  If you use the default setup without additional features (like `logmod`,
  `logonly`, `logcatch`, `tofile`), then in most cases `nolog` will only
  work on compile-time macros without using functions, methods, `if`
  or loops. In fact it will expand into
  the string `eprintln!("{}", format_args!("{}{}{}{}","   ", "CRIT⧽", "msg", "[34] src/main.rs"));`.
  Nothing extra.
- Filtering by module path (`logmod` feature).
- Display messages only from a selected section of code (`logonly` feature).
- Smart logging: hide all messages, show the previous `Х` messages
  if an `error` or `crit` level message was triggered (`logcatch` feature).
- A custom indent can be added to the message, as well as a number
  of blank lines before and after it. You can use variables (eg loop
  counter) to set the indent for the selected message.
- Easily adjust and disable all indents and newlines with features.
- Сustomization: you can create your own color scheme for the logger.
- Support for named format arguments: `info!("{line_count} lines.");`.
- Support for `key => value` syntax: `info!("{server}" => "{ip}");`
- Automatically disabled in the release build: `cargo run --release`.
  If you want the log to be enabled in the release build, then use
  `release` feature: `nolog = {version = "*", features = ["release"]}`.
- All levels are disabled by default. Turning on the `debug` level also
  turns on the levels above it: `info`, `warn`, `error`, `crit`.
  Level can be enabled using the console:
  `cargo run --features debug` or in `Cargo.toml`:
  `nolog = {version = "*", features = ["debug"]}`. 
  To enable all levels: `cargo run --features trace`.
- By default, the log is writting to `stderr`. You can log to a file with
  `tofile` feature. You may set the buffer size. Automatic flush after
  each message will be used. If you want wait for the buffer to fill
  or to do it manually with `logflush!()` then use `no_auto_flush` feature.
- [Custom output redirection]#custom-output-redirection. For example, to a `file` and to `stderr`
  at the same time.
- You can add a timestamp like `[2022-07-10 06:49:33.646361181 UTC]`
  using a third party library you like. [How to add a timestamp]#how-to-add-a-timestamp.
- Support for chaining multiple messages into one (they must all be
  of the same type: `usual` or `key-value`): 
```rust
info!(
        "{server}" => "{ip}";
        "Status"   => "{server_check_result}";
);
```

## Table of contents

- [Using nolog]#using-nolog
- [Using nolog with `--features`]#using-nolog-with---features
- [Tofile. Writing log entries to a file]#tofile-writing-log-entries-to-a-file
- [How to add a timestamp]#how-to-add-a-timestamp
- [Styles]#styles
- [Chaining]#chaining
- [Logmod. Filtering by module path]#logmod-filtering-by-module-path
- [Logonly. Display messages only from a selected section of code]#logonly-display-messages-only-from-a-selected-section-of-code
- [Logcatch. Smart logging]#logcatch-smart-logging
- [Quick disable and enable messages]#quick-disable-and-enable-messages
- [Indentation and new lines]#indentation-and-new-lines
- [Colors]#colors
- [Level headers]#level-headers
- [Don't disable logger in release build]#dont-disable-logger-in-release-build
- [Location]#location
- [Separator]#separator
- [Custom color scheme]#custom-color-scheme
- [Custom output redirection]#custom-output-redirection
- [Other customization options]#other-customization-options
- [Logging in tests]#logging-in-tests
- [Changelog]#changelog

## Using nolog

**Cargo.toml**

```toml
[dependencies]
nolog = { version = "1", features = ["trace"] }
```

**main.rs**

```rust
#[macro_use]
extern crate nolog;

fn main() {
    trace!("line_count: {}", 42);
    debug!("line_count: {}", 42);
    info!("line_count: {}", 42);
    warn!("line_count: {}", 42);
    error!("line_count: {}", 42);
    crit!("line_count: {}", 42);
}
```

```sh
cargo run
```

**Result:**

![example](https://raw.githubusercontent.com/vglinka/nolog/main/assets/min_2.png)

You can enable more output filtering features in `cargo.toml`:

 - [Logonly]#logonly-display-messages-only-from-a-selected-section-of-code. Display messages only from a selected section of code. Useful with `trace` level.
- [Logcatch]#logcatch-smart-logging. Smart logging. Hide all messages, show the previous `Х` messages if an `error` or `crit` level message was triggered. Allows you to understand what preceded the error.
- [Logmod]#logmod-filtering-by-module-path. Filtering by module path. Receive messages only from the module you are currently working on.

**Cargo.toml**

```toml
[dependencies]
nolog = { version = "1", features = [
  "debug",
  "logonly",
  "logcatch",
  "logmod",
]}
```

In addition, you can customize the appearance settings.

![styles](https://raw.githubusercontent.com/vglinka/nolog/main/assets/style_2.gif)

Appearance settings `classic`:

**Cargo.toml**

```toml
[dependencies]
nolog = { version = "1", features = [
  "debug",
  "show_lvl_header_kv",
  "indent_ignore_all",
  "newline_ignore",
  "location_style_classic",
  "sep_colon",
]}
```

Appearance settings `classic_plain`:

**Cargo.toml**

```toml
[dependencies]
nolog = { version = "1", features = [
  "debug",
  "plain",
  "show_lvl_header_kv",
  "indent_ignore_all",
  "newline_ignore",
  "location_style_classic",
  "sep_colon",
]}
```

**Indentation.**

You can specify indentation in the following way:

`crit!(->[X,Y,Z] "msg");`

- `X` - Indents.
- `Y` - Add `Y` blank lines **before** message.
- `Z` - Add `Z` blank lines **after** message.

All of these arguments are optional:

```rust
crit!("msg");

//       X
crit!(->[1] "msg");

//       X Y
crit!(->[6,1] "msg");

//       X Y Z
crit!(->[1,2,3] "msg");
```

If you want to add blank lines and leave the default indentation:

```rust
//       X Y
crit!(->[_,1] "msg");

//       X Y Z
crit!(->[_,_,2] "msg");
```

The same works for each message in the chain.

```rust
debug!(
    ->[2]   "msg 1";
    ->[_,1] "msg 2";
            "msg 3";
);
```

Key-values ​​have the additional ability to set indentation not only
for the key, but also for the value.

```rust
debug!(->[_,1] "The simulation server started successfully.");
debug!(
    "{server}" =>       "{ip}";
    "Status"   => ->[3] "{server_check_result}";
);
crit!(->[_,1] "The Universe was created with a lifetime of {} days.", universe.len());
```

This allows you to get nice aligned output if you want.

![indent](https://raw.githubusercontent.com/vglinka/nolog/main/assets/indent_3.png)

Read more about [indentation](#indentation-and-new-lines).

[↑ Table of contents ↑](#table-of-contents)

## Using nolog with `--features`

You need to completely copy the contents of this file to your `cargo.toml`.
Then you can write `cargo run --features trace,logonly` instead of 
`cargo run --features nolog/trace,nolog/logonly` [See example on GitHub](https://github.com/vglinka/nolog/tree/main/examples/min_example).

**Cargo.toml**

```toml
[dependencies]
nolog = { version = "1", features = [] }

[features]
nolog_setup = []

# example `classic`
#nolog_setup = ["nolog/show_lvl_header_kv", "nolog/indent_ignore_all", "nolog/newline_ignore", "nolog/location_style_classic", "nolog/sep_colon"]

# example `classic_plain`
#nolog_setup = ["nolog/plain", "nolog/show_lvl_header_kv", "nolog/indent_ignore_all", "nolog/newline_ignore", "nolog/location_style_classic", "nolog/sep_colon"]

trace = ["nolog/trace", "nolog_setup"]
debug = ["nolog/debug", "nolog_setup"]
info  = ["nolog/info",  "nolog_setup"]
warn  = ["nolog/warn",  "nolog_setup"]
error = ["nolog/error", "nolog_setup"]
crit  = ["nolog/crit",  "nolog_setup"]

logonly  = ["nolog/logonly"]
logcatch = ["nolog/logcatch"]
logmod   = ["nolog/logmod"]
```

The commented lines `nolog_setup = ["nolog/show_lvl_h...]` are
the [appearance](#styles) settings (indents, color scheme, styles, etc).
Uncomment one of them to see what happens (don't forget
to remove `nolog_setup = []`).

Appearance settings are selected using conditional compilation,
so they have a zero cost.


**main.rs**

```rust
#[macro_use]
extern crate nolog;

fn main() {
    trace!("line_count: {}", 42);
    debug!("line_count: {}", 42);
    info!("line_count: {}", 42);
    warn!("line_count: {}", 42);
    error!("line_count: {}", 42);
    crit!("line_count: {}", 42);
}
```

[This example on GitHub](https://github.com/vglinka/nolog/tree/main/examples/min_example).

`nolog` has the same syntax as most loggers based on the `log` crate.
`nolog` extends the `log` crate syntax by adding new features.
However, `nolog` is not based on `log` crate, it just has the same
macro names. This also results in the `nolog` having 0 dependencies.

Therefore, switching to `nolog` will require minimal changes in the code.

Ok. Now we can use the following command:

```sh
cargo run --features trace
```

Or, for example

```sh
# The output will be empty because there are no logonly
# blocks, etc. in the code.
# This is just to demonstrate the use of several features.

cargo run --features trace,logonly,logcatch,logmod
```

It's the same but noisier

```sh
# The output will be empty because there are no logonly
# blocks, etc. in the code.
# This is just to demonstrate the use of several features.

cargo run --features nolog/trace,nolog/logonly,nolog/logcatch,nolog/logmod
```

**Result:**

![example](https://raw.githubusercontent.com/vglinka/nolog/main/assets/min.png)

[↑ Table of contents ↑](#table-of-contents)

## Tofile. Writing log entries to a file

**Cargo.toml**

```toml
#...
[dependencies]
nolog = { version = "1", features = ["tofile"] }
#...
```

**main.rs**

```rust
use std::fs::OpenOptions;
use std::io::{self, Read};
use std::path::PathBuf;

#[macro_use]
extern crate nolog;

fn main() -> io::Result<()> {
    let path = PathBuf::from("log.txt");
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(true)
        //^^^^^^^ truncate the file to 0 length if it already exists.
        //.append(true)
        .open(&path)?;
        
    // Initialization
    // Don't use macros like `debug!("msg");` before initialization.
    logfile!(file);
    
    trace!("Hello from file!");
        
    let mut file = OpenOptions::new()
        .read(true)
        .open(&path)?;
    
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    println!("\n      -- In {path:?} --");
    println!("{contents}");
    
    Ok(())
}
```

[This example on GitHub](https://github.com/vglinka/nolog/tree/main/examples/tofile).

Optionally, you can set the buffer size.

```rust
    // Buffer `std::io::BufWriter` with capacity: 8000 bytes.
    logfile!(8000, file);
```

The default is to automatically flush after each message.
If you want wait for the buffer to fill or to do it manually
with `logflush!()` then use `no_auto_flush` feature.

**Cargo.toml**

```toml
#...
[dependencies]
nolog = { version = "1", features = ["tofile", "no_auto_flush"] }
#...
```

Then use `logflush!()` to flush the log manually.

**main.rs**

```rust
...
    // Initialization
    // Don't use macros like `debug!("msg");` before initialization.
    logfile!(8000, file);
    
    trace!("Hello from file!");
    logflush!();     
...
```

[↑ Table of contents ↑](#table-of-contents)

## How to add a timestamp

You can add a timestamp like `[2022-07-10 06:49:33.646361181 UTC]`
using a third party library you like.

For this example, we will use `chrono` crate.

**Cargo.toml**

```toml
#...
[dependencies]
nolog = { version = "1", features = [] }
chrono = "0.4"

[features]
custom_leading    = ["nolog/custom_leading"]
custom_trailing   = ["nolog/custom_trailing"]
custom_before_msg = ["nolog/custom_before_msg"]
custom_after_msg  = ["nolog/custom_after_msg"]

nolog_setup = ["custom_leading"]
#...
```

We have 4 options here:
- "custom_leading" - `<TIMESTAMP>CRIT⧽ msg [5] src/main.rs`
- "custom_trailing" - `CRIT⧽ msg [5] src/main.rs<TIMESTAMP>`
- "custom_before_msg" - `CRIT⧽ <TIMESTAMP>msg [5] src/main.rs`
- "custom_after_msg" - `CRIT⧽ msg<TIMESTAMP> [5] src/main.rs`

Log entry structure:

usual:
`<indents><custom_leading><lvlheader><sep><custom_before_msg><msg><custom_after_msg><location><custom_trailing>`

key-value:
`<indents><custom_leading><lvlheader><sep_kv><custom_before_msg><key><sep_key><value_indent><value><custom_after_msg><location><custom_trailing>`

Here is an example:

**main.rs**

```rust
#[macro_use]
extern crate nolog;

#[macro_use] 
pub mod logger_setup {
    #[macro_export]
    #[cfg(feature = "custom_leading")] macro_rules!
    //               ^^^^^^^^^^^^^^
    custom_leading { 
        // usual
        ( $level:tt, $indent:expr, $($msg:expr),* ) => {
            format_args!("[{}] ", chrono::Utc::now())
            
        };
        // key-value
        ( $level:tt, $indent:expr, $($key:expr),* => $($value:expr),* ) => {
            format_args!("[{}] ", chrono::Local::now())
        };
    }
}

mod other {
    pub fn from_other_mod() -> () {
        crit!(->[0] "Other" => "Hello from other mod! This is key-value msg.");
    }
}

fn main() {
    crit!("Hello from main! This is usual msg.");
    other::from_other_mod();   
}
```

[This example on GitHub](https://github.com/vglinka/nolog/tree/main/examples/timestamp).

Output:

```sh
[2022-09-07 09:22:09.150921578 UTC] CRIT⧽ Hello from main! This is usual msg. [34] src/main.rs
[2022-09-07 12:22:09.150973037 +03:00] Other⧽ Hello from other mod! This is key-value msg. [29] src/main.rs

```

With `classic` style:

```sh
[2022-09-07 09:29:45.859185734 UTC] CRIT: Hello from main! This is usual msg. [src/main.rs 34:5]
[2022-09-07 12:29:45.859225186 +03:00] CRIT: Other: Hello from other mod! This is key-value msg. [src/main.rs 29:9]
```

[↑ Table of contents ↑](#table-of-contents)

## Styles

#### Default
```toml
nolog_setup = []
```

#### `classic`

```toml
nolog_setup = ["nolog/show_lvl_header_kv", "nolog/indent_ignore_all", "nolog/newline_ignore", "nolog/location_style_classic", "nolog/sep_colon"]
```

#### `classic_plain`

```toml
nolog_setup = ["nolog/plain", "nolog/show_lvl_header_kv", "nolog/indent_ignore_all", "nolog/newline_ignore", "nolog/location_style_classic", "nolog/sep_colon"]
```

![styles](https://raw.githubusercontent.com/vglinka/nolog/main/assets/style.gif)

[↑ Table of contents ↑](#table-of-contents)

## Chaining

Messages in a chain should all be of the same type: `usual` or `key-value`

**ususal**

```rust
debug!(
    "Planet {name} thinks...";
    "Planet {name} thinks...";
);
```

**key-value**

```rust
debug!(
    "{server}" => "{ip}";
    "Status"   => "{server_check_result}";
);
```

[↑ Table of contents ↑](#table-of-contents)

## Logmod. Filtering by module path

Add it as early as possible in the code:

```rust
logmod!(
    [  ] main,
    [!=] crate::other2,
);
```

- `[]`   - Include a module and all its submodules.
- `[=]`  - the same (Include a module and all its submodules).
- `[!]`  - Exclude a module and all its submodules.
- `[==]` - Include only this module without submodules.
- `[!=]` - Exclude only this module without submodules.

Then

`cargo run --features trace,logmod`

[↑ Table of contents ↑](#table-of-contents)

## Logonly. Display messages only from a selected section of code

This is useful for debugging to get messages from just a small
piece of code. 

```rust
logonly!(
    let universe = [0;3];
    crit!("The Universe was created with a lifetime of {} days.", universe.len());
    error!("Uncontrolled evolutionary processes have begun on the planet {planet_name}.");
);
```

Then

`cargo run --features trace,logonly`

You can use any brackets

`logonly!()`, `logonly!{}`, `logonly![]`.

You can use multiple `logonly!()` blocks. Messages will be displayed from all.

It won't break your code when the logger turns off in release build.
So you can leave these blocks in the code.

When disabled, the definition of this macro will be replaced with
the following:

```rust
logonly { ( $($a:tt)* ) => { $($a)* }; }
```

It simply writes down the code it received.

[↑ Table of contents ↑](#table-of-contents)

## Logcatch. Smart logging

Hide all messages, show the previous `Х` messages if an `error` or `crit`
level message was triggered.

By default `X=10`. You can change this anywhere in the code.

```rust
// This will take effect for the code below.
logcatch!(2); // now X=2
```

To enable this feature, use:

`cargo run --features trace,logcatch`

Each new line created with `newline!()` or `->[_,1,1]`(about
what it will be below) counts as a separate message.

[↑ Table of contents ↑](#table-of-contents)

## Quick disable and enable messages

You can disable individual messages without removing them from the code.
A macro like `debug!([_]; "msg")` will expand into an empty tuple `()`.

```rust
// on
info!([#]; "New {name} on planet {planet_name}.");

// off
info!([_]; "{repr}" => "{name} says: {speech}");
```

You can use any options you like:

**On:**
`[#]`, `[x]`, `[v]`, `[+]`, `[on]`, `[true]`, `[your_var]`

**Off:**
`[ ]`, `[_]`, `[-]`, `[off]`, `[false]`, `[your_var]`

`your_var` should be `bool`.

To change states, you need to change only one character:

`[_]` --> `[#]`.

This also works with chained messages, but disables the entire chain.
You can't turn off a single message in a chain.

```rust
crit!([_];
    "The answer is {answer}."; 
    "Planet {planet_name} started watching TV.";
);
```

You can turn off the action of block `logonly`. This will not affect
the code, the effect is as if macro `logonly` was not in this place.

```rust
logonly!{[_];
    crit!("The answer is {answer}.");
    let x = 42;
}
```

This way you can leave `logonly!()` in the code and if it is required
in the future just enable it.

[↑ Table of contents ↑](#table-of-contents)

#### Variables and expressions

If necessary, you can control messages using variables and expressions.

```rust
let my_log_enabled = true;
crit!([my_log_enabled]; "The planet {} has been destroyed.", self.name);
```

```rust
let status = "ok";
crit!([(status == "ok")]; "The planet {} has been destroyed.", self.name);
//     ^              ^
//     Add parentheses
```

```rust
fn is_message_show_fn () -> bool { false }
...
crit!([(is_message_show_fn())]; "The planet {} has been destroyed.", self.name);
//     ^                    ^
//     Add parentheses
```

[↑ Table of contents ↑](#table-of-contents)

## Indentation and new lines

### new lines

`newline!(2);` - It will simply write the passed number of new lines to the log.

### Indentation

Indents are of several types:

#### Base indent

Base indent will be added to every line.
- Default for all: `6` indents. One indent equals one space.

You can change `base indent` with cargo features:

- `indent_base_zero`
- `indent_base_one`
- `indent_base_two`
- `indent_base_three`
- `indent_base_four`
- `indent_base_five`
- `indent_base_seven`
- `indent_base_eight`
- `indent_base_nine`
- `indent_base_ten`

For example in `Cargo.toml`: 

```toml
nolog_setup = ["nolog/indent_base_zero"]

trace = ["nolog/trace", "nolog_setup"]
```

#### The indent of the selected message

- Default for `usual`: 0
- Default for `key-value`: 6

The default indentation is used if no value has been provided by the user.

You can specify indentation in the following way:

`crit!(->[X,Y,Z] "msg");`

- `X` - Indents.
- `Y` - Add `Y` blank lines before message (same effect as `newline!(Y)`).
- `Z` - Add `Z` blank lines after message.

All of these arguments are optional:

```rust
crit!("msg");
crit!(->[1] "msg");
crit!(->[6,1] "msg");
crit!(->[1,2,3] "msg");
crit!([#]; ->[1,2,3] "msg");
```

If you want to add blank lines and leave the default indentation:

```rust
crit!(->[_,1] "msg");
crit!(->[_,_,2] "msg");
```

The same works for each message in the chain.

```rust
debug!(
    ->[2]   "Planet {name} thinks...";
    ->[_,1] "Planet {name} thinks...";
            "Planet {name} thinks...";
);
```

`key => value` ​​have an indentation of `6` by default, but you can reset
it by setting it to zero.

```rust
error!(->[0] "{name}" => "{}!! Oh, yeaaaah!", 2*3*7);
```

Or you can do it via `Cargo.toml` for all messages.

- `indent_kv_default_zero`
- `indent_kv_default_one`
- `indent_kv_default_two`
- `indent_kv_default_three`
- `indent_kv_default_four`
- `indent_kv_default_five`
- `indent_kv_default_seven`
- `indent_kv_default_eight`
- `indent_kv_default_nine`
- `indent_kv_default_ten`

For example in `Cargo.toml`:
```toml
nolog_setup = ["nolog/indent_kv_default_zero"]

trace = ["nolog/trace", "nolog_setup"]
```

Key-values ​​have the additional ability to set indentation not only
for the key, but also for the value.

```rust
debug!(
    "{server}" =>       "{ip}";
    "Status"   => ->[3] "{server_check_result}";
);
```

This allows you to get nice aligned output if you want.

![indent](https://raw.githubusercontent.com/vglinka/nolog/main/assets/indent_1.png)

#### Indent variables

You can use variables to set the indentation and add blank lines.

```rust
for i in 0..2 {
    warn!(->[i,i,i] "msg");
}
```

#### Ignore all indents

Ignore all types of indentation.

```toml
nolog_setup = ["nolog/indent_ignore_all"]
```

![indent](https://raw.githubusercontent.com/vglinka/nolog/main/assets/indent_2.png)

#### Ignore all newlines

```toml
nolog_setup = ["nolog/newline_ignore"]
```

[↑ Table of contents ↑](#table-of-contents)

## Colors

`nolog` colored by default, use this feature for plain output:

```toml
nolog_setup = ["nolog/plain"]
```

[↑ Table of contents ↑](#table-of-contents)

## Level headers

```toml
nolog_setup = ["nolog/show_lvl_header_kv"]
```

Show level name for key-value:
```sh
CRIT: Key: value [src/main.rs 90:5]`
^^^^
```

It's disabled by default: 
```sh
Key: value [src/main.rs 90:5]
```

[↑ Table of contents ↑](#table-of-contents)

## Don't disable logger in release build

```toml
nolog = { version = "1", features = ["release"] }
```

[↑ Table of contents ↑](#table-of-contents)

## Location

Don't show location (like `[src/main.rs 155:9]`)

```toml
nolog_setup = ["nolog/location_hide"]
```

Style like this: `[src/main.rs 155:9]`

```toml
nolog_setup = ["nolog/location_style_classic"]
```

![location](https://raw.githubusercontent.com/vglinka/nolog/main/assets/location.gif)

[↑ Table of contents ↑](#table-of-contents)

## Separator

Default = "⧽ "

- ": "

```toml
nolog_setup = ["nolog/sep_colon"]
```

- " "

```toml
nolog_setup = ["nolog/sep_space"]
```


- ""

```toml
nolog_setup = ["nolog/sep_hide"]
```

[↑ Table of contents ↑](#table-of-contents)

## Custom color scheme

You can create your own color scheme for the logger.

**Cargo.toml**

```toml
#...
[dependencies]
nolog = { version = "1", features = [] }

[features]
custom_colors = ["nolog/custom_colors"]
nolog_setup = ["custom_colors"]
#...
```

Here is an example:

**main.rs**

```rust
#[macro_use]
extern crate nolog;

#[macro_use] 
pub mod logger_setup {
    #[macro_export]
    #[cfg(feature = "custom_colors")] macro_rules!
    //               ^^^^^^^^^^^^^
    color {
        ( [trace] ) => { "\x1B[34m"                    };
        ( [debug] ) => { "\x1B[36m"                    };
        ( [info]  ) => { "\x1B[32m"                    };
        ( [warn]  ) => { "\x1B[33m"                    };
        ( [error] ) => { "\x1B[31m"                    };
        ( [crit]  ) => { "\x1B[35m"                    };
        ( [sep]   ) => { "\x1B[1m\x1B[2m"              }; // +bold +dim
        ( [msg]   ) => { ""                            }; // default term font color
        ( [from]  ) => { "\x1B[90m\x1B[3m"             }; // `[src/main.rs 101:5]` in `location_style_classic`
        ( [sep2]  ) => { "\x1B[90m\x1B[2m"             }; // sep2 in default style
        ( [sep3]  ) => { "\x1B[90m\x1B[2m"             }; // sep3 in default style
        ( [line]  ) => { "\x1B[38;5;67m\x1B[1m\x1B[2m" }; // line number in default style
        ( [key]   ) => { "\x1B[3m\x1B[1m"              }; // +italic +bold 
        ( [value] ) => { "\x1B[3m"                     }; // +italic
        ( [rm]    ) => { "\x1B[0m"                     }; // remove previous colors
    }
}

mod other {
    pub fn from_other_mod() -> () {
        crit!(->[0] "Other" => "Hello from other mod! This is key-value msg.");
    }
}

fn main(){
    crit!("Hello from main! This is usual msg.");
    other::from_other_mod();   
}
```

[This example on GitHub](https://github.com/vglinka/nolog/tree/main/examples/custom_color_scheme).

[↑ Table of contents ↑](#table-of-contents)

## Custom output redirection

It is possible to redirect output. For example, we will redirect
output to stderr and to a file at the same time. The limitation is that
output to stderr will be the same as to a file, it will not be colorized.

**Cargo.toml**

```toml
#...
[dependencies]
nolog = { version = "1", features = [] }

[features]
nolog_setup = [
    "custom_writelog_inner",
    "nolog/tofile"
]
custom_writelog_inner = ["nolog/custom_writelog_inner"]
#...
```

Here is an example:

**main.rs**

```rust
use std::fs::OpenOptions;
use std::io::{self, Read};
use std::path::PathBuf;

#[macro_use]
extern crate nolog;

// use `cargo run --features trace`

#[macro_use] 
pub mod logger_setup {
    #[macro_export]
    #[cfg(feature = "custom_writelog_inner")] macro_rules!
    writelog_inner { ( $msg:expr ) => {
            eprintln!("{}", $msg); // write to stderr
            tofile_writelog_inner_helper!($msg); // write to a file
        }
    }
}

mod other {
    pub fn from_other_mod() -> () {
        crit!(->[0] "Other" => "Hello from other mod! This is key-value msg.");
    }
}

fn main() -> io::Result<()> {
    let path = PathBuf::from("log.txt");
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(true)
        //^^^^^^^ truncate the file to 0 length if it already exists.
        //.append(true)
        .open(&path)?;
        
    // Initialization
    // Don't use macros like `debug!("msg");` before initialization.
    logfile!(file);
    
    eprintln!("\n-- From eprintln: --");
    crit!("Hello from main! This is usual msg.");
    other::from_other_mod();
    
    let mut file = OpenOptions::new()
        .read(true)
        .open(&path)?;
    
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    println!("\n-- In {path:?} --");
    println!("{contents}");
    
    Ok(())
}
```

[This example on GitHub](https://github.com/vglinka/nolog/tree/main/examples/custom_output_redirection).

Output:

```sh
-- From eprintln: --
CRIT: Hello from main! This is usual msg. [main.rs 54:5]
CRIT: Other: Hello from other mod! This is key-value msg. [main.rs 34:9]

-- In "log.txt" --
CRIT: Hello from main! This is usual msg. [main.rs 54:5]
CRIT: Other: Hello from other mod! This is key-value msg. [main.rs 34:9]

```

[↑ Table of contents ↑](#table-of-contents)

## Other customization options

`nolog` has other customization options not described here, since
it is unlikely that they will be in demand by a wide range of users.
Their use is similar to that described above.
You can see the full up-to-date list in
[Cargo.toml](https://github.com/vglinka/nolog/tree/main/Cargo.toml).

[↑ Table of contents ↑](#table-of-contents)

## Logging in tests

Logging in tests works exactly the same, except that Rust test programs
hide standard output of successful tests.

Use the following code to see the output of successful tests.

```sh
cargo test --features trace -- --nocapture
```

The output of failed tests will be displayed anyway.

```sh
cargo test --features trace
```

[↑ Table of contents ↑](#table-of-contents)

## Changelog

- **1.0.15 - 1.0.19** – Small changes in Readme etc.
- **1.0.12 - 1.0.14** – Small changes in Readme etc. Minor optimization fixes.
- **1.0.10 - 1.0.11** – Minor changes, an example with output redirection has been added.
- **1.0.1 - 1.0.9** – Small changes in Readme etc.
- **1.0.0** – Release. Completely rewritten.
- **0.1.1-0.2.3** – Early versions.