1+ // Copyright © Serilog Contributors
2+ //
3+ // Licensed under the Apache License, Version 2.0 (the "License");
4+ // you may not use this file except in compliance with the License.
5+ // You may obtain a copy of the License at
6+ //
7+ // http://www.apache.org/licenses/LICENSE-2.0
8+ //
9+ // Unless required by applicable law or agreed to in writing, software
10+ // distributed under the License is distributed on an "AS IS" BASIS,
11+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+ // See the License for the specific language governing permissions and
13+ // limitations under the License.
14+
15+ using Serilog . Expressions ;
16+ using Serilog . Parsing ;
17+ using Serilog . Templates . Rendering ;
18+ using Serilog . Templates . Themes ;
19+
20+ namespace Serilog . Templates . Compilation ;
21+
22+ class CompiledTimestampToken : CompiledTemplate
23+ {
24+ readonly string ? _format ;
25+ readonly Alignment ? _alignment ;
26+ readonly IFormatProvider ? _formatProvider ;
27+ readonly Style _secondaryText ;
28+
29+ public CompiledTimestampToken ( string ? format , Alignment ? alignment , IFormatProvider ? formatProvider , TemplateTheme theme )
30+ {
31+ _format = format ;
32+ _alignment = alignment ;
33+ _formatProvider = formatProvider ;
34+ _secondaryText = theme . GetStyle ( TemplateThemeStyle . SecondaryText ) ;
35+ }
36+
37+ public override void Evaluate ( EvaluationContext ctx , TextWriter output )
38+ {
39+ var invisibleCharacterCount = 0 ;
40+
41+ if ( _alignment == null )
42+ {
43+ EvaluateUnaligned ( ctx , output , _formatProvider , ref invisibleCharacterCount ) ;
44+ }
45+ else
46+ {
47+ var writer = new StringWriter ( ) ;
48+ EvaluateUnaligned ( ctx , writer , _formatProvider , ref invisibleCharacterCount ) ;
49+ Padding . Apply ( output , writer . ToString ( ) , _alignment . Value . Widen ( invisibleCharacterCount ) ) ;
50+ }
51+ }
52+
53+ void EvaluateUnaligned ( EvaluationContext ctx , TextWriter output , IFormatProvider ? formatProvider , ref int invisibleCharacterCount )
54+ {
55+ var value = ctx . LogEvent . Timestamp ;
56+
57+ using var style = _secondaryText . Set ( output , ref invisibleCharacterCount ) ;
58+
59+ #if FEATURE_SPAN
60+ Span < char > buffer = stackalloc char [ 36 ] ;
61+ if ( value . TryFormat ( buffer , out int charsWritten , _format , _formatProvider ) )
62+ {
63+ output . Write ( buffer [ ..charsWritten ] ) ;
64+ return ;
65+ }
66+ #endif
67+ output . Write ( value . ToString ( _format , formatProvider ) ) ;
68+
69+ }
70+ }
0 commit comments