├── global.json ├── .editorconfig ├── test ├── MessageTemplates.Net35Tests │ ├── NuGet.config │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── packages.config │ └── MessageTemplates.Net35Tests.csproj ├── MessageTemplates.Net40Tests │ ├── NuGet.config │ ├── packages.config │ ├── Properties │ │ └── AssemblyInfo.cs │ └── MessageTemplates.Net40Tests.csproj └── MessageTemplates.Tests │ ├── MessageTemplates.Tests.csproj │ ├── Formatting │ └── JsonValueFormatterTests.cs │ ├── ParserTests.cs │ └── FormatTests.cs ├── appveyor.yml ├── src └── MessageTemplates │ ├── Core │ ├── IMessageTemplateParser.cs │ ├── IScalarConversionPolicy.cs │ ├── ILogEventPropertyValueFactory.cs │ ├── Padding.cs │ ├── TemplatePropertyValueDictionary.cs │ ├── ScalarTemplatePropertyValueDictionary.cs │ ├── IDestructuringPolicy.cs │ ├── ILogEventPropertyFactory.cs │ ├── TemplatePropertyList.cs │ └── TemplatePropertyValueList.cs │ ├── Parsing │ ├── AlignmentDirection.cs │ ├── Destructuring.cs │ ├── Alignment.cs │ ├── MessageTemplateToken.cs │ ├── TextToken.cs │ ├── PropertyToken.cs │ └── MessageTemplateParser.cs │ ├── Policies │ ├── DelegateDestructuringPolicy.cs │ ├── ReflectionTypesScalarDestructuringPolicy.cs │ ├── EnumScalarConversionPolicy.cs │ ├── SimpleScalarConversionPolicy.cs │ ├── ProjectedDestructuringPolicy.cs │ ├── ByteArrayScalarConversionPolicy.cs │ └── NullableScalarConversionPolicy.cs │ ├── Debugging │ ├── LoggingFailedException.cs │ └── SelfLog.cs │ ├── Parameters │ ├── GetablePropertyFinder.cs │ ├── DepthLimiter.cs │ ├── PropertyBinder.cs │ └── PropertyValueConverter.cs │ ├── Structure │ ├── TemplateProperty.cs │ ├── SequenceValue.cs │ ├── DictionaryValue.cs │ ├── TemplatePropertyValue.cs │ ├── StructureValue.cs │ └── ScalarValue.cs │ ├── MessageTemplates.csproj │ ├── Data │ └── TemplatePropertyValueVisitor.cs │ ├── MessageTemplate.cs │ └── Formatting │ └── JsonValueFormatter.cs ├── Build.ps1 ├── MessageTemplates.sln ├── .gitattributes ├── README.md ├── .gitignore └── LICENSE /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "2.1.104" 4 | } 5 | } -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root=true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 4 6 | -------------------------------------------------------------------------------- /test/MessageTemplates.Net35Tests/NuGet.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /test/MessageTemplates.Net40Tests/NuGet.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /test/MessageTemplates.Net35Tests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("MessageTemplates.Net35Tests")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("MessageTemplates.Net35Tests")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | -------------------------------------------------------------------------------- /test/MessageTemplates.Tests/MessageTemplates.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net452;netcoreapp1.0;netcoreapp2.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | version: '{build}' 2 | image: Visual Studio 2017 3 | configuration: Release 4 | install: 5 | - ps: mkdir -Force ".\build\" | Out-Null 6 | - ps: Invoke-WebRequest "https://dot.net/v1/dotnet-install.ps1" -OutFile ".\build\installcli.ps1" 7 | - ps: $env:DOTNET_INSTALL_DIR = "$pwd\.dotnetcli" 8 | - ps: '& .\build\installcli.ps1 -InstallDir "$env:DOTNET_INSTALL_DIR" -NoPath -Version 2.1.104' 9 | - ps: $env:Path = "$env:DOTNET_INSTALL_DIR;$env:Path" 10 | build_script: 11 | - ps: ./Build.ps1 12 | artifacts: 13 | - path: artifacts/MessageTemplates.*.nupkg 14 | deploy: 15 | - provider: NuGet 16 | api_key: 17 | secure: ZdlULX6DI2b/fKecXcFFuKZmMP+q2lz+us4pAeGqFl7mK0Be2/hG7LDSfZgIgAKI 18 | skip_symbols: true 19 | on: 20 | branch: /^(dev|master)$/ 21 | 22 | -------------------------------------------------------------------------------- /test/MessageTemplates.Net35Tests/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /test/MessageTemplates.Net40Tests/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/MessageTemplates/Core/IMessageTemplateParser.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 | namespace MessageTemplates.Core 16 | { 17 | interface IMessageTemplateParser 18 | { 19 | MessageTemplate Parse(string messageTemplate); 20 | } 21 | } -------------------------------------------------------------------------------- /src/MessageTemplates/Core/IScalarConversionPolicy.cs: -------------------------------------------------------------------------------- 1 | 2 | using MessageTemplates.Structure; 3 | 4 | namespace MessageTemplates.Core 5 | { 6 | /// 7 | /// Determine how a simple value is carried through the logging 8 | /// pipeline as an immutable . 9 | /// 10 | interface IScalarConversionPolicy 11 | { 12 | /// 13 | /// If supported, convert the provided value into an immutable scalar. 14 | /// 15 | /// The value to convert. 16 | /// Recursively apply policies to convert additional values. 17 | /// The converted value, or null. 18 | /// True if the value could be converted under this policy. 19 | bool TryConvertToScalar(object value, IMessageTemplatePropertyValueFactory propertyValueFactory, out ScalarValue result); 20 | } 21 | } -------------------------------------------------------------------------------- /src/MessageTemplates/Core/ILogEventPropertyValueFactory.cs: -------------------------------------------------------------------------------- 1 | using MessageTemplates.Structure; 2 | 3 | namespace MessageTemplates.Core 4 | { 5 | /// 6 | /// Supports the policy-driven construction of s given 7 | /// regular .NET objects. 8 | /// 9 | public interface IMessageTemplatePropertyValueFactory 10 | { 11 | /// 12 | /// Create a given a .NET object and destructuring 13 | /// strategy. 14 | /// 15 | /// The value of the property. 16 | /// If true, and the value is a non-primitive, non-array type, 17 | /// then the value will be converted to a structure; otherwise, unknown types will 18 | /// be converted to scalars, which are generally stored as strings. 19 | /// The value. 20 | TemplatePropertyValue CreatePropertyValue(object value, bool destructureObjects = false); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/MessageTemplates/Core/Padding.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using MessageTemplates.Parsing; 3 | 4 | namespace MessageTemplates.Formatting.Display 5 | { 6 | static class Padding 7 | { 8 | /// 9 | /// Writes the provided value to the output, applying direction-based padding when is provided. 10 | /// 11 | public static void Apply(TextWriter output, string value, Alignment? alignment) 12 | { 13 | if (!alignment.HasValue) 14 | { 15 | output.Write(value); 16 | return; 17 | } 18 | 19 | var pad = alignment.Value.Width - value.Length; 20 | 21 | if (alignment.Value.Direction == AlignmentDirection.Right) 22 | output.Write(new string(' ', pad)); 23 | 24 | output.Write(value); 25 | 26 | if (alignment.Value.Direction == AlignmentDirection.Left) 27 | output.Write(new string(' ', pad)); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /src/MessageTemplates/Core/TemplatePropertyValueDictionary.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using MessageTemplates.Structure; 4 | 5 | namespace MessageTemplates.Core 6 | { 7 | /// 8 | /// 9 | /// 10 | public class TemplatePropertyValueDictionary 11 | { 12 | private Dictionary props; 13 | 14 | /// 15 | /// 16 | /// 17 | /// 18 | public TemplatePropertyValueDictionary(TemplatePropertyList props) 19 | { 20 | this.props = props.ToDictionary(p => p.Name, p=> p.Value); 21 | } 22 | 23 | /// 24 | /// 25 | /// 26 | /// 27 | /// 28 | /// 29 | public bool TryGetValue(string propertyName, out TemplatePropertyValue propertyValue) 30 | { 31 | return props.TryGetValue(propertyName, out propertyValue); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/MessageTemplates/Parsing/AlignmentDirection.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 | namespace MessageTemplates.Parsing 16 | { 17 | /// 18 | /// Defines the direction of the alignment. 19 | /// 20 | public enum AlignmentDirection 21 | { 22 | /// 23 | /// Text will be left-aligned. 24 | /// 25 | Left, 26 | /// 27 | /// Text will be right-aligned. 28 | /// 29 | Right 30 | } 31 | } -------------------------------------------------------------------------------- /src/MessageTemplates/Policies/DelegateDestructuringPolicy.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 System; 16 | using MessageTemplates.Core; 17 | using MessageTemplates.Structure; 18 | 19 | namespace MessageTemplates.Policies 20 | { 21 | class DelegateDestructuringPolicy : IDestructuringPolicy 22 | { 23 | public bool TryDestructure(object value, IMessageTemplatePropertyValueFactory propertyValueFactory, out TemplatePropertyValue result) 24 | { 25 | if (value is Delegate del) 26 | { 27 | result = new ScalarValue(del.ToString()); 28 | return true; 29 | } 30 | 31 | result = null; 32 | return false; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/MessageTemplates/Debugging/LoggingFailedException.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 System; 16 | 17 | namespace MessageTemplates.Debugging 18 | { 19 | /// 20 | /// May be thrown by log event sinks when a failure occurs. Should not be used in cases 21 | /// where the exception would propagate out to callers. 22 | /// 23 | public class LoggingFailedException : Exception 24 | { 25 | /// 26 | /// Construct a to communicate a logging failure. 27 | /// 28 | /// A message describing the logging failure. 29 | public LoggingFailedException(string message) 30 | : base(message) 31 | { 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/MessageTemplates/Core/ScalarTemplatePropertyValueDictionary.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using MessageTemplates.Structure; 4 | using System.Linq; 5 | 6 | namespace MessageTemplates.Core 7 | { 8 | /// 9 | /// 10 | /// 11 | public class ScalarTemplatePropertyValueDictionary 12 | : IEnumerable> 13 | { 14 | private IDictionary elements; 15 | 16 | /// 17 | /// 18 | /// 19 | /// 20 | public ScalarTemplatePropertyValueDictionary( 21 | IEnumerable> elements) 22 | { 23 | this.elements = elements.ToDictionary(e => e.Key, e => e.Value); 24 | } 25 | 26 | /// 27 | /// 28 | /// 29 | /// 30 | public IEnumerator> GetEnumerator() 31 | { 32 | return elements.GetEnumerator(); 33 | } 34 | 35 | /// 36 | /// 37 | /// 38 | /// 39 | IEnumerator IEnumerable.GetEnumerator() 40 | { 41 | return GetEnumerator(); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /src/MessageTemplates/Parsing/Destructuring.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 | namespace MessageTemplates.Parsing 16 | { 17 | /// 18 | /// Instructs the logger on how to store information about provided 19 | /// parameters. 20 | /// 21 | public enum Destructuring 22 | { 23 | /// 24 | /// Convert known types and objects to scalars, arrays to sequences. 25 | /// 26 | Default, 27 | 28 | /// 29 | /// Convert all types to scalar strings. Prefix name with '$'. 30 | /// 31 | Stringify, 32 | 33 | /// 34 | /// Convert known types to scalars, destructure objects and collections 35 | /// into sequences and structures. Prefix name with '@'. 36 | /// 37 | Destructure 38 | } 39 | } -------------------------------------------------------------------------------- /src/MessageTemplates/Policies/ReflectionTypesScalarDestructuringPolicy.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2016 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 System; 16 | using System.Reflection; 17 | using MessageTemplates.Core; 18 | using MessageTemplates.Structure; 19 | 20 | namespace MessageTemplates.Policies 21 | { 22 | class ReflectionTypesScalarDestructuringPolicy : IDestructuringPolicy 23 | { 24 | public bool TryDestructure(object value, IMessageTemplatePropertyValueFactory propertyValueFactory, out TemplatePropertyValue result) 25 | { 26 | // These types and their subclasses are property-laden and deep; 27 | // most sinks will convert them to strings. 28 | if (value is Type || value is MemberInfo) 29 | { 30 | result = new ScalarValue(value); 31 | return true; 32 | } 33 | 34 | result = null; 35 | return false; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /test/MessageTemplates.Net40Tests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("MessageTemplates.Net40Tests")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("MessageTemplates.Net40Tests")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("481d8962-9efd-4470-bf83-87a761581367")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/MessageTemplates/Policies/EnumScalarConversionPolicy.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 System.Reflection; 16 | using MessageTemplates.Core; 17 | using MessageTemplates.Structure; 18 | 19 | namespace MessageTemplates.Policies 20 | { 21 | class EnumScalarConversionPolicy : IScalarConversionPolicy 22 | { 23 | public bool TryConvertToScalar(object value, IMessageTemplatePropertyValueFactory propertyValueFactory, out ScalarValue result) 24 | { 25 | bool isEnum = false; 26 | #if !REFLECTION_API_EVOLVED // https://blogs.msdn.microsoft.com/dotnet/2012/08/28/evolving-the-reflection-api/ 27 | isEnum = value.GetType().IsEnum; 28 | #else 29 | isEnum = value.GetType().GetTypeInfo().IsEnum; 30 | #endif 31 | 32 | if (isEnum) 33 | { 34 | result = new ScalarValue(value); 35 | return true; 36 | } 37 | 38 | result = null; 39 | return false; 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/MessageTemplates/Policies/SimpleScalarConversionPolicy.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 System; 16 | using System.Collections.Generic; 17 | using MessageTemplates.Core; 18 | using MessageTemplates.Structure; 19 | 20 | namespace MessageTemplates.Policies 21 | { 22 | class SimpleScalarConversionPolicy : IScalarConversionPolicy 23 | { 24 | readonly HashSet _scalarTypes; 25 | 26 | public SimpleScalarConversionPolicy(IEnumerable scalarTypes) 27 | { 28 | _scalarTypes = new HashSet(scalarTypes); 29 | } 30 | 31 | public bool TryConvertToScalar(object value, IMessageTemplatePropertyValueFactory propertyValueFactory, out ScalarValue result) 32 | { 33 | if (_scalarTypes.Contains(value.GetType())) 34 | { 35 | result = new ScalarValue(value); 36 | return true; 37 | } 38 | 39 | result = null; 40 | return false; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/MessageTemplates/Core/IDestructuringPolicy.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 MessageTemplates.Structure; 16 | 17 | namespace MessageTemplates.Core 18 | { 19 | /// 20 | /// Determine how, when destructuring, a supplied value is represented 21 | /// as a complex log event property. 22 | /// 23 | public interface IDestructuringPolicy 24 | { 25 | /// 26 | /// If supported, destructure the provided value. 27 | /// 28 | /// The value to destructure. 29 | /// Recursively apply policies to destructure additional values. 30 | /// The destructured value, or null. 31 | /// True if the value could be destructured under this policy. 32 | bool TryDestructure(object value, IMessageTemplatePropertyValueFactory propertyValueFactory, out TemplatePropertyValue result); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/MessageTemplates/Parsing/Alignment.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 | namespace MessageTemplates.Parsing 16 | { 17 | /// 18 | /// A structure representing the alignment settings to apply when rendering a property. 19 | /// 20 | public struct Alignment 21 | { 22 | /// 23 | /// Initializes a new instance of . 24 | /// 25 | /// The text alignment direction. 26 | /// The width of the text, in characters. 27 | public Alignment(AlignmentDirection direction, int width) 28 | { 29 | Direction = direction; 30 | Width = width; 31 | } 32 | 33 | /// 34 | /// The text alignment direction. 35 | /// 36 | public AlignmentDirection Direction { get; } 37 | 38 | /// 39 | /// The width of the text. 40 | /// 41 | public int Width { get; } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/MessageTemplates/Core/ILogEventPropertyFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 MessageTemplates.Structure; 16 | 17 | namespace MessageTemplates.Core 18 | { 19 | /// 20 | /// Creates log event properties from regular .NET objects, applying policies as 21 | /// required. 22 | /// 23 | public interface ILogEventPropertyFactory 24 | { 25 | /// 26 | /// Construct a with the specified name and value. 27 | /// 28 | /// The name of the property. 29 | /// The value of the property. 30 | /// If true, and the value is a non-primitive, non-array type, 31 | /// then the value will be converted to a structure; otherwise, unknown types will 32 | /// be converted to scalars, which are generally stored as strings. 33 | /// 34 | TemplateProperty CreateProperty(string name, object value, bool destructureObjects = false); 35 | } 36 | } -------------------------------------------------------------------------------- /src/MessageTemplates/Parameters/GetablePropertyFinder.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 | #if REFLECTION_API_EVOLVED // https://blogs.msdn.microsoft.com/dotnet/2012/08/28/evolving-the-reflection-api/ 16 | using System; 17 | using System.Collections.Generic; 18 | using System.Linq; 19 | using System.Reflection; 20 | 21 | namespace MessageTemplates.Parameters 22 | { 23 | static class GetablePropertyFinder 24 | { 25 | internal static IEnumerable GetPropertiesRecursive(this Type type) 26 | { 27 | var seenNames = new HashSet(); 28 | 29 | var currentTypeInfo = type.GetTypeInfo(); 30 | 31 | while (currentTypeInfo.AsType() != typeof(object)) 32 | { 33 | var unseenProperties = currentTypeInfo.DeclaredProperties.Where(p => p.CanRead && 34 | p.GetMethod.IsPublic && !p.GetMethod.IsStatic && 35 | (p.Name != "Item" || p.GetIndexParameters().Length == 0) && !seenNames.Contains(p.Name)); 36 | 37 | foreach (var propertyInfo in unseenProperties) 38 | { 39 | seenNames.Add(propertyInfo.Name); 40 | yield return propertyInfo; 41 | } 42 | 43 | currentTypeInfo = currentTypeInfo.BaseType.GetTypeInfo(); 44 | } 45 | } 46 | } 47 | } 48 | #endif -------------------------------------------------------------------------------- /src/MessageTemplates/Core/TemplatePropertyList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using MessageTemplates.Structure; 5 | 6 | namespace MessageTemplates.Core 7 | { 8 | /// 9 | /// 10 | /// 11 | public class TemplatePropertyList : IEnumerable 12 | { 13 | private readonly TemplateProperty[] result; 14 | 15 | /// 16 | /// 17 | /// 18 | /// 19 | public TemplatePropertyList(TemplateProperty[] result) 20 | { 21 | if (result == null) throw new ArgumentNullException(nameof(result)); 22 | this.result = result; 23 | } 24 | 25 | /// 26 | /// 27 | /// 28 | public int Length => result.Length; 29 | 30 | /// 31 | /// 32 | /// 33 | public int Count => result.Length; 34 | 35 | /// 36 | /// 37 | /// 38 | /// 39 | /// 40 | public TemplateProperty this[int index] => result[index]; 41 | 42 | /// Returns an enumerator that iterates through a collection. 43 | /// An object that can be used to iterate 44 | /// through the collection. 45 | public IEnumerator GetEnumerator() 46 | { 47 | return ((IEnumerable) result).GetEnumerator(); 48 | } 49 | 50 | /// Returns an enumerator that iterates through a collection. 51 | /// An object that can be used to iterate through the collection. 52 | IEnumerator IEnumerable.GetEnumerator() 53 | { 54 | return GetEnumerator(); 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /src/MessageTemplates/Policies/ProjectedDestructuringPolicy.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 System; 16 | using MessageTemplates.Core; 17 | using MessageTemplates.Structure; 18 | 19 | namespace MessageTemplates.Policies 20 | { 21 | class ProjectedDestructuringPolicy : IDestructuringPolicy 22 | { 23 | readonly Func _canApply; 24 | readonly Func _projection; 25 | 26 | public ProjectedDestructuringPolicy(Func canApply, Func projection) 27 | { 28 | if (canApply == null) throw new ArgumentNullException(nameof(canApply)); 29 | if (projection == null) throw new ArgumentNullException(nameof(projection)); 30 | _canApply = canApply; 31 | _projection = projection; 32 | } 33 | 34 | public bool TryDestructure(object value, IMessageTemplatePropertyValueFactory propertyValueFactory, out TemplatePropertyValue result) 35 | { 36 | if (value == null) throw new ArgumentNullException(nameof(value)); 37 | 38 | if (!_canApply(value.GetType())) 39 | { 40 | result = null; 41 | return false; 42 | } 43 | 44 | var projected = _projection(value); 45 | result = propertyValueFactory.CreatePropertyValue(projected, true); 46 | return true; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/MessageTemplates/Policies/ByteArrayScalarConversionPolicy.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 System.Linq; 16 | using MessageTemplates.Core; 17 | using MessageTemplates.Structure; 18 | 19 | namespace MessageTemplates.Policies 20 | { 21 | // Byte arrays, when logged, need to be copied so that they are 22 | // safe from concurrent modification when written to asynchronous 23 | // sinks. Byte arrays larger than 1k are written as descriptive strings. 24 | class ByteArrayScalarConversionPolicy : IScalarConversionPolicy 25 | { 26 | const int MaximumByteArrayLength = 1024; 27 | 28 | public bool TryConvertToScalar(object value, IMessageTemplatePropertyValueFactory propertyValueFactory, out ScalarValue result) 29 | { 30 | var bytes = value as byte[]; 31 | if (bytes == null) 32 | { 33 | result = null; 34 | return false; 35 | } 36 | 37 | if (bytes.Length > MaximumByteArrayLength) 38 | { 39 | var start = string.Concat(bytes.Take(16).Select(b => b.ToString("X2"))); 40 | var description = $"{start}... ({bytes.Length} bytes)"; 41 | result = new ScalarValue(description); 42 | } 43 | else 44 | { 45 | result = new ScalarValue(bytes.ToArray()); 46 | } 47 | 48 | return true; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/MessageTemplates/Core/TemplatePropertyValueList.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using MessageTemplates.Structure; 5 | 6 | namespace MessageTemplates.Core 7 | { 8 | /// 9 | /// 10 | /// 11 | public class TemplatePropertyValueList : IEnumerable 12 | { 13 | private readonly TemplatePropertyValue[] _elements; 14 | 15 | /// 16 | /// 17 | /// 18 | /// 19 | public TemplatePropertyValueList(IEnumerable elements) 20 | { 21 | this._elements = elements.ToArray(); 22 | } 23 | 24 | /// 25 | /// 26 | /// 27 | public int Length => _elements.Length; 28 | 29 | /// 30 | /// 31 | /// 32 | public int Count => _elements.Length; 33 | 34 | /// 35 | /// 36 | /// 37 | /// 38 | /// 39 | public TemplatePropertyValue this[int index] => _elements[index]; 40 | 41 | /// Returns an enumerator that iterates through the collection. 42 | /// An enumerator that can be used to iterate through the collection. 43 | public IEnumerator GetEnumerator() 44 | { 45 | for (int index = 0; index < _elements.Length; index++) 46 | { 47 | var templateProperty = _elements[index]; 48 | yield return templateProperty; 49 | } 50 | } 51 | 52 | /// Returns an enumerator that iterates through a collection. 53 | /// An object that can be used to iterate through the collection. 54 | IEnumerator IEnumerable.GetEnumerator() 55 | { 56 | return GetEnumerator(); 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /Build.ps1: -------------------------------------------------------------------------------- 1 | Push-Location $PSScriptRoot 2 | 3 | if(Test-Path .\artifacts) { Remove-Item .\artifacts -Force -Recurse } 4 | 5 | & dotnet restore 6 | 7 | $branch = @{ $true = $env:APPVEYOR_REPO_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$env:APPVEYOR_REPO_BRANCH -ne $NULL]; 8 | $revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:APPVEYOR_BUILD_NUMBER, 10); $false = "local" }[$env:APPVEYOR_BUILD_NUMBER -ne $NULL]; 9 | $suffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)))-$revision"}[$branch -eq "master" -and $revision -ne "local"] 10 | 11 | echo "build: Version suffix is '$suffix'" 12 | 13 | Push-Location src\MessageTemplates 14 | 15 | # always use revision for now, need to fix before 1.0 release 16 | & dotnet pack -c Release --include-symbols --include-source -o ..\..\artifacts --version-suffix=$revision 17 | if($LASTEXITCODE -ne 0) { exit 1 } 18 | 19 | Pop-Location 20 | 21 | Push-Location test\MessageTemplates.Tests 22 | 23 | & dotnet test -c Release 24 | if($LASTEXITCODE -ne 0) { exit 2 } 25 | 26 | Pop-Location 27 | 28 | Push-Location test\MessageTemplates.Net40Tests 29 | 30 | &nuget install ..\..\test\MessageTemplates.Net40Tests\packages.config -SolutionDirectory ..\..\ 31 | 32 | &msbuild ..\..\test\MessageTemplates.Net40Tests\MessageTemplates.Net40Tests.csproj /p:Configuration=Release 33 | if($LASTEXITCODE -ne 0) { exit 2 } 34 | 35 | & ..\..\packages\xunit.runner.console.2.2.0-beta1-build3239\tools\xunit.console.x86.exe ..\..\test\MessageTemplates.Net40Tests\bin\Release\MessageTemplates.Net40Tests.dll 36 | 37 | if($LASTEXITCODE -ne 0) { exit 2 } 38 | 39 | Pop-Location 40 | 41 | 42 | Push-Location 43 | 44 | &nuget install test\MessageTemplates.Net35Tests\packages.config -SolutionDirectory . 45 | 46 | &msbuild test\MessageTemplates.Net35Tests\MessageTemplates.Net35Tests.csproj /p:Configuration=Release 47 | if($LASTEXITCODE -ne 0) { exit 2 } 48 | 49 | & packages\xunit.runner.console.2.2.0-beta1-build3239\tools\xunit.console.x86.exe test\MessageTemplates.Net35Tests\bin\Release\MessageTemplates.Net35Tests.dll 50 | 51 | if($LASTEXITCODE -ne 0) { exit 2 } 52 | 53 | Pop-Location 54 | -------------------------------------------------------------------------------- /src/MessageTemplates/Policies/NullableScalarConversionPolicy.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 System; 16 | using MessageTemplates.Core; 17 | using MessageTemplates.Structure; 18 | 19 | namespace MessageTemplates.Policies 20 | { 21 | class NullableScalarConversionPolicy : IScalarConversionPolicy 22 | { 23 | public bool TryConvertToScalar(object value, IMessageTemplatePropertyValueFactory propertyValueFactory, out ScalarValue result) 24 | { 25 | var type = value.GetType(); 26 | #if !REFLECTION_API_EVOLVED 27 | if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Nullable<>)) 28 | #else 29 | if (!type.IsConstructedGenericType || type.GetGenericTypeDefinition() != typeof(Nullable<>)) 30 | #endif 31 | { 32 | result = null; 33 | return false; 34 | } 35 | #if USE_DYNAMIC 36 | var dynamicValue = (dynamic)value; 37 | var innerValue = dynamicValue.HasValue ? (object)dynamicValue.Value : null; 38 | #elif !REFLECTION_API_EVOLVED 39 | var targetType = type.GetGenericArguments()[0]; 40 | var innerValue = Convert.ChangeType(value, targetType, null); 41 | #else 42 | var targetType = type.GenericTypeArguments[0]; 43 | var innerValue = Convert.ChangeType(value, targetType); 44 | #endif 45 | result = propertyValueFactory.CreatePropertyValue(innerValue) as ScalarValue; 46 | return result != null; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /MessageTemplates.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27428.2037 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Assets", "Assets", "{E38800B5-71BD-437D-9441-1B7E16662EA1}" 7 | ProjectSection(SolutionItems) = preProject 8 | .editorconfig = .editorconfig 9 | appveyor.yml = appveyor.yml 10 | build.cmd = build.cmd 11 | Build.ps1 = Build.ps1 12 | global.json = global.json 13 | LICENSE = LICENSE 14 | README.md = README.md 15 | EndProjectSection 16 | EndProject 17 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MessageTemplates", "src\MessageTemplates\MessageTemplates.csproj", "{D3F08EB6-8E19-48B4-9D1B-79740BA3265C}" 18 | EndProject 19 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MessageTemplates.Tests", "test\MessageTemplates.Tests\MessageTemplates.Tests.csproj", "{1B6D4995-CE6E-4EB2-8728-B8FAA1999E28}" 20 | EndProject 21 | Global 22 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 23 | Debug|Any CPU = Debug|Any CPU 24 | Release|Any CPU = Release|Any CPU 25 | EndGlobalSection 26 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 27 | {D3F08EB6-8E19-48B4-9D1B-79740BA3265C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {D3F08EB6-8E19-48B4-9D1B-79740BA3265C}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {D3F08EB6-8E19-48B4-9D1B-79740BA3265C}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {D3F08EB6-8E19-48B4-9D1B-79740BA3265C}.Release|Any CPU.Build.0 = Release|Any CPU 31 | {1B6D4995-CE6E-4EB2-8728-B8FAA1999E28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {1B6D4995-CE6E-4EB2-8728-B8FAA1999E28}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {1B6D4995-CE6E-4EB2-8728-B8FAA1999E28}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {1B6D4995-CE6E-4EB2-8728-B8FAA1999E28}.Release|Any CPU.Build.0 = Release|Any CPU 35 | EndGlobalSection 36 | GlobalSection(SolutionProperties) = preSolution 37 | HideSolutionNode = FALSE 38 | EndGlobalSection 39 | GlobalSection(ExtensibilityGlobals) = postSolution 40 | SolutionGuid = {4B0F514C-3C89-4F4E-8350-A0089DFAD4E9} 41 | EndGlobalSection 42 | EndGlobal 43 | -------------------------------------------------------------------------------- /src/MessageTemplates/Debugging/SelfLog.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 System; 16 | using System.IO; 17 | 18 | namespace MessageTemplates.Debugging 19 | { 20 | /// 21 | /// A simple source of information generated by Message Templates itself, 22 | /// for example when exceptions are thrown and caught internally. 23 | /// 24 | public static class SelfLog 25 | { 26 | /// 27 | /// The output mechanism for self-log events. 28 | /// 29 | /// 30 | /// SelfLog.Out = Console.Error; 31 | /// 32 | // ReSharper disable once MemberCanBePrivate.Global, UnusedAutoPropertyAccessor.Global 33 | public static TextWriter Out { get; set; } 34 | 35 | /// 36 | /// Write a message to the self-log. 37 | /// 38 | /// Standard .NET format string containing the message. 39 | /// First argument, if supplied. 40 | /// Second argument, if supplied. 41 | /// Third argument, if supplied. 42 | public static void WriteLine(string format, object arg0 = null, object arg1 = null, object arg2 = null) 43 | { 44 | var o = Out; 45 | if (o != null) 46 | { 47 | o.WriteLine(DateTime.Now.ToString("s") + " " + format, arg0, arg1, arg2); 48 | o.Flush(); 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/MessageTemplates/Parsing/MessageTemplateToken.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 System; 16 | using System.IO; 17 | using MessageTemplates.Core; 18 | 19 | namespace MessageTemplates.Parsing 20 | { 21 | /// 22 | /// An element parsed from a message template string. 23 | /// 24 | public abstract class MessageTemplateToken 25 | { 26 | /// 27 | /// Construct a . 28 | /// 29 | /// The token's start index in the template. 30 | protected MessageTemplateToken(int startIndex) 31 | { 32 | StartIndex = startIndex; 33 | } 34 | 35 | /// 36 | /// The token's start index in the template. 37 | /// 38 | // ReSharper disable once UnusedAutoPropertyAccessor.Global 39 | public int StartIndex { get; } 40 | 41 | /// 42 | /// The token's length. 43 | /// 44 | public abstract int Length { get; } 45 | 46 | 47 | 48 | /// 49 | /// Render the token to the output. 50 | /// 51 | /// Properties that may be represented by the token. 52 | /// Output for the rendered string. 53 | /// Supplies culture-specific formatting information, or null. 54 | public abstract void Render( 55 | TemplatePropertyValueDictionary properties, 56 | TextWriter output, 57 | IFormatProvider formatProvider = null); 58 | } 59 | } -------------------------------------------------------------------------------- /src/MessageTemplates/Parameters/DepthLimiter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 MessageTemplates.Core; 16 | using MessageTemplates.Debugging; 17 | using MessageTemplates.Parsing; 18 | using MessageTemplates.Structure; 19 | 20 | namespace MessageTemplates.Parameters 21 | { 22 | partial class PropertyValueConverter 23 | { 24 | class DepthLimiter : IMessageTemplatePropertyValueFactory 25 | { 26 | readonly int _maximumDestructuringDepth; 27 | readonly int _currentDepth; 28 | readonly PropertyValueConverter _propertyValueConverter; 29 | 30 | public DepthLimiter(int currentDepth, int maximumDepth, PropertyValueConverter propertyValueConverter) 31 | { 32 | _maximumDestructuringDepth = maximumDepth; 33 | _currentDepth = currentDepth; 34 | _propertyValueConverter = propertyValueConverter; 35 | } 36 | 37 | public TemplatePropertyValue CreatePropertyValue(object value, Destructuring destructuring) 38 | { 39 | return DefaultIfMaximumDepth() ?? 40 | _propertyValueConverter.CreatePropertyValue(value, destructuring, _currentDepth + 1); 41 | } 42 | 43 | public TemplatePropertyValue CreatePropertyValue(object value, bool destructureObjects = false) 44 | { 45 | return DefaultIfMaximumDepth() ?? 46 | _propertyValueConverter.CreatePropertyValue(value, destructureObjects, _currentDepth + 1); 47 | } 48 | 49 | TemplatePropertyValue DefaultIfMaximumDepth() 50 | { 51 | if (_currentDepth == _maximumDestructuringDepth) 52 | { 53 | SelfLog.WriteLine("Maximum destructuring depth reached."); 54 | return new ScalarValue(null); 55 | } 56 | 57 | return null; 58 | } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/MessageTemplates/Structure/TemplateProperty.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 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 System; 16 | 17 | namespace MessageTemplates.Structure 18 | { 19 | /// 20 | /// A property associated with a . 21 | /// 22 | public class TemplateProperty 23 | { 24 | /// 25 | /// Construct a with the specified name and value. 26 | /// 27 | /// The name of the property. 28 | /// The value of the property. 29 | /// 30 | /// 31 | public TemplateProperty(string name, TemplatePropertyValue value) 32 | { 33 | if (value == null) throw new ArgumentNullException("value"); 34 | if (!IsValidName(name)) 35 | throw new ArgumentException("Property name is not valid."); 36 | 37 | Name = name; 38 | Value = value; 39 | } 40 | 41 | /// 42 | /// The name of the property. 43 | /// 44 | public string Name { get; } 45 | 46 | /// 47 | /// The value of the property. 48 | /// 49 | public TemplatePropertyValue Value { get; } 50 | 51 | /// 52 | /// Test to determine if it is a valid property name. 53 | /// 54 | /// The name to check. 55 | /// True if the name is valid; otherwise, false. 56 | public static bool IsValidName(string name) 57 | { 58 | #if NO_STRING_ISNULLORWHITESPACE 59 | if (name == null) return false; 60 | if (string.IsNullOrEmpty(name.Trim())) 61 | return false; 62 | return true; 63 | #else 64 | return !string.IsNullOrWhiteSpace(name); 65 | #endif 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /src/MessageTemplates/MessageTemplates.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Message templates - the ability to format named string values, and capture the properties 5 | 1.0.0-rc 6 | Serilog Contributors;Adam Chester 7 | net452;net35;net40;netstandard1.0;netstandard1.3 8 | true 9 | MessageTemplates 10 | MessageTemplates 11 | message;template;serilog;logging;semantic;structured 12 | http://messagetemplates.org/images/messagetemplates-nuget.png 13 | https://github.com/messagetemplates/messagetemplates-csharp 14 | http://www.apache.org/licenses/LICENSE-2.0 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | $(MSBuildProgramFiles32)\Reference Assemblies\Microsoft\Framework\.NETFramework\v3.5\Profile\Client 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | $(DefineConstants);REFLECTION_API_EVOLVED 46 | 47 | 48 | 49 | $(DefineConstants);REFLECTION_API_EVOLVED 50 | 51 | 52 | 53 | $(DefineConstants);REFLECTION_API_EVOLVED 54 | 55 | 56 | 57 | $(DefineConstants);NO_STRING_ISNULLORWHITESPACE 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /src/MessageTemplates/Structure/SequenceValue.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 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 System; 16 | using System.Collections.Generic; 17 | using System.IO; 18 | using MessageTemplates.Core; 19 | 20 | namespace MessageTemplates.Structure 21 | { 22 | /// 23 | /// A value represented as an ordered sequence of values. 24 | /// 25 | public class SequenceValue : TemplatePropertyValue 26 | { 27 | /// 28 | /// Create a with the provided . 29 | /// 30 | /// The elements of the sequence. 31 | /// 32 | public SequenceValue(IEnumerable elements) 33 | { 34 | if (elements == null) throw new ArgumentNullException("elements"); 35 | Elements = new TemplatePropertyValueList(elements); 36 | } 37 | 38 | /// 39 | /// The elements of the sequence. 40 | /// 41 | public TemplatePropertyValueList Elements { get; } 42 | 43 | /// 44 | /// Render the value to the output. 45 | /// 46 | /// The output. 47 | /// A format string applied to the value, or null. 48 | /// A format provider to apply to the value, or null to use the default. 49 | /// . 50 | public override void Render(TextWriter output, string format = null, IFormatProvider formatProvider = null) 51 | { 52 | if (output == null) throw new ArgumentNullException("output"); 53 | 54 | output.Write('['); 55 | var allButLast = Elements.Length - 1; 56 | for (var i = 0; i < allButLast; ++i ) 57 | { 58 | Elements[i].Render(output, format, formatProvider); 59 | output.Write(", "); 60 | } 61 | 62 | if (Elements.Length > 0) 63 | Elements[Elements.Length - 1].Render(output, format, formatProvider); 64 | 65 | output.Write(']'); 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /src/MessageTemplates/Structure/DictionaryValue.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 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 System; 16 | using System.Collections.Generic; 17 | using System.IO; 18 | using MessageTemplates.Core; 19 | 20 | namespace MessageTemplates.Structure 21 | { 22 | /// 23 | /// A value represented as a mapping from keys to values. 24 | /// 25 | public class DictionaryValue : TemplatePropertyValue 26 | { 27 | 28 | /// 29 | /// Create a with the provided . 30 | /// 31 | /// The key-value mappings represented in the dictionary. 32 | /// 33 | public DictionaryValue(IEnumerable> elements) 34 | { 35 | if (elements == null) throw new ArgumentNullException("elements"); 36 | Elements = new ScalarTemplatePropertyValueDictionary(elements); 37 | } 38 | 39 | /// 40 | /// The dictionary mapping. 41 | /// 42 | public ScalarTemplatePropertyValueDictionary Elements { get; } 43 | 44 | /// 45 | /// Render the value to the output. 46 | /// 47 | /// The output. 48 | /// A format string applied to the value, or null. 49 | /// A format provider to apply to the value, or null to use the default. 50 | /// . 51 | public override void Render(TextWriter output, string format = null, IFormatProvider formatProvider = null) 52 | { 53 | if (output == null) throw new ArgumentNullException("output"); 54 | 55 | output.Write('['); 56 | var delim = "("; 57 | foreach (var kvp in Elements) 58 | { 59 | output.Write(delim); 60 | delim = ", ("; 61 | kvp.Key.Render(output, null, formatProvider); 62 | output.Write(": "); 63 | kvp.Value.Render(output, null, formatProvider); 64 | output.Write(")"); 65 | } 66 | 67 | output.Write(']'); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/MessageTemplates/Structure/TemplatePropertyValue.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 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 System; 16 | using System.IO; 17 | 18 | namespace MessageTemplates.Structure 19 | { 20 | /// 21 | /// The value associated with a . Divided into scalar, 22 | /// sequence and structure values to direct serialization into various formats. 23 | /// 24 | public abstract class TemplatePropertyValue : IFormattable 25 | { 26 | /// 27 | /// Render the value to the output. 28 | /// 29 | /// The output. 30 | /// A format string applied to the value, or null. 31 | /// A format provider to apply to the value, or null to use the default. 32 | /// . 33 | public abstract void Render(TextWriter output, string format = null, IFormatProvider formatProvider = null); 34 | 35 | /// 36 | /// Returns a string that represents the current object. 37 | /// 38 | /// 39 | /// A string that represents the current object. 40 | /// 41 | /// 2 42 | public override string ToString() 43 | { 44 | return ToString(null, null); 45 | } 46 | 47 | /// 48 | /// Formats the value of the current instance using the specified format. 49 | /// 50 | /// 51 | /// The value of the current instance in the specified format. 52 | /// 53 | /// The format to use.-or- A null reference (Nothing in Visual Basic) to use 54 | /// the default format defined for the type of the implementation. 55 | /// The provider to use to format the value.-or- A null reference 56 | /// (Nothing in Visual Basic) to obtain the numeric format information from the current locale 57 | /// setting of the operating system. 2 58 | public string ToString(string format, IFormatProvider formatProvider) 59 | { 60 | var output = new StringWriter(); 61 | Render(output, format, formatProvider); 62 | return output.ToString(); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/MessageTemplates/Parsing/TextToken.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 System; 16 | using System.IO; 17 | using MessageTemplates.Core; 18 | 19 | namespace MessageTemplates.Parsing 20 | { 21 | /// 22 | /// A message template token representing literal text. 23 | /// 24 | public class TextToken : MessageTemplateToken 25 | { 26 | /// 27 | /// Construct a . 28 | /// 29 | /// The text of the token. 30 | /// The token's start index in the template. 31 | /// 32 | public TextToken(string text, int startIndex = -1) : base(startIndex) 33 | { 34 | if (text == null) throw new ArgumentNullException(nameof(text)); 35 | Text = text; 36 | } 37 | 38 | /// 39 | /// The token's length. 40 | /// 41 | public override int Length => Text.Length; 42 | 43 | /// 44 | /// Render the token to the output. 45 | /// 46 | /// Properties that may be represented by the token. 47 | /// Output for the rendered string. 48 | /// Supplies culture-specific formatting information, or null. 49 | public override void Render(TemplatePropertyValueDictionary properties, TextWriter output, IFormatProvider formatProvider = null) 50 | { 51 | if (output == null) throw new ArgumentNullException(nameof(output)); 52 | output.Write(Text); 53 | } 54 | 55 | /// 56 | /// Determines whether the specified is equal to the current . 57 | /// 58 | /// 59 | /// true if the specified object is equal to the current object; otherwise, false. 60 | /// 61 | /// The object to compare with the current object. 2 62 | public override bool Equals(object obj) 63 | { 64 | return obj is TextToken tt && tt.Text == Text; 65 | } 66 | 67 | /// 68 | /// Serves as a hash function for a particular type. 69 | /// 70 | /// 71 | /// A hash code for the current . 72 | /// 73 | /// 2 74 | public override int GetHashCode() => Text.GetHashCode(); 75 | 76 | /// 77 | /// Returns a string that represents the current object. 78 | /// 79 | /// 80 | /// A string that represents the current object. 81 | /// 82 | /// 2 83 | public override string ToString() => Text; 84 | 85 | /// 86 | /// The text of the token. 87 | /// 88 | public string Text { get; } 89 | } 90 | } -------------------------------------------------------------------------------- /src/MessageTemplates/Structure/StructureValue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | // Copyright 2014 Serilog Contributors 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | using System.IO; 18 | using System.Linq; 19 | using MessageTemplates.Core; 20 | 21 | namespace MessageTemplates.Structure 22 | { 23 | /// 24 | /// A value represented as a collection of name-value properties. 25 | /// 26 | public class StructureValue : TemplatePropertyValue 27 | { 28 | /// 29 | /// Construct a with the provided properties. 30 | /// 31 | /// Optionally, a piece of metadata describing the "type" of the 32 | /// structure. 33 | /// The properties of the structure. 34 | /// 35 | public StructureValue(IEnumerable properties, string typeTag = null) 36 | { 37 | if (properties == null) throw new ArgumentNullException("properties"); 38 | TypeTag = typeTag; 39 | Properties = new TemplatePropertyList(properties.ToArray()); 40 | } 41 | 42 | /// 43 | /// A piece of metadata describing the "type" of the 44 | /// structure, or null. 45 | /// 46 | public string TypeTag { get; } 47 | 48 | /// 49 | /// The properties of the structure. 50 | /// 51 | /// Not presented as a dictionary because dictionary construction is 52 | /// relatively expensive; it is cheaper to build a dictionary over properties only 53 | /// when the structure is of interest. 54 | public TemplatePropertyList Properties { get; } 55 | 56 | /// 57 | /// Render the value to the output. 58 | /// 59 | /// The output. 60 | /// A format string applied to the value, or null. 61 | /// A format provider to apply to the value, or null to use the default. 62 | /// . 63 | public override void Render(TextWriter output, string format = null, IFormatProvider formatProvider = null) 64 | { 65 | if (output == null) throw new ArgumentNullException("output"); 66 | 67 | if (TypeTag != null) 68 | { 69 | output.Write(TypeTag); 70 | output.Write(' '); 71 | } 72 | output.Write("{ "); 73 | var allButLast = Properties.Length - 1; 74 | for (var i = 0; i < allButLast; i++) 75 | { 76 | var property = Properties[i]; 77 | Render(output, property, formatProvider); 78 | output.Write(", "); 79 | } 80 | 81 | if (Properties.Length > 0) 82 | { 83 | var last = Properties[Properties.Length - 1]; 84 | Render(output, last, formatProvider); 85 | } 86 | 87 | output.Write(" }"); 88 | } 89 | 90 | static void Render(TextWriter output, TemplateProperty property, IFormatProvider formatProvider = null) 91 | { 92 | output.Write(property.Name); 93 | output.Write(": "); 94 | property.Value.Render(output, null, formatProvider); 95 | } 96 | } 97 | } -------------------------------------------------------------------------------- /src/MessageTemplates/Structure/ScalarValue.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 System; 16 | using System.Globalization; 17 | using System.IO; 18 | 19 | namespace MessageTemplates.Structure 20 | { 21 | /// 22 | /// A property value corresponding to a simple, scalar type. 23 | /// 24 | public class ScalarValue : TemplatePropertyValue 25 | { 26 | /// 27 | /// Construct a with the specified 28 | /// value. 29 | /// 30 | /// The value, which may be null. 31 | public ScalarValue(object value) 32 | { 33 | Value = value; 34 | } 35 | 36 | /// 37 | /// The value, which may be null. 38 | /// 39 | public object Value { get; } 40 | 41 | /// 42 | /// Render the value to the output. 43 | /// 44 | /// The output. 45 | /// A format string applied to the value, or null. 46 | /// A format provider to apply to the value, or null to use the default. 47 | /// . 48 | public override void Render(TextWriter output, string format = null, IFormatProvider formatProvider = null) 49 | { 50 | if (output == null) throw new ArgumentNullException(nameof(output)); 51 | 52 | if (Value == null) 53 | { 54 | output.Write("null"); 55 | return; 56 | } 57 | 58 | if (Value is string s) 59 | { 60 | if (format != "l") 61 | { 62 | output.Write("\""); 63 | output.Write(s.Replace("\"", "\\\"")); 64 | output.Write("\""); 65 | } 66 | else 67 | { 68 | output.Write(s); 69 | } 70 | return; 71 | } 72 | 73 | if (formatProvider != null) 74 | { 75 | var custom = (ICustomFormatter)formatProvider.GetFormat(typeof(ICustomFormatter)); 76 | if (custom != null) 77 | { 78 | output.Write(custom.Format(format, Value, formatProvider)); 79 | return; 80 | } 81 | } 82 | 83 | if (Value is IFormattable f) 84 | { 85 | output.Write(f.ToString(format, formatProvider ?? CultureInfo.InvariantCulture)); 86 | } 87 | else 88 | { 89 | output.Write(Value.ToString()); 90 | } 91 | } 92 | 93 | /// 94 | /// Determine if this instance is equal to . 95 | /// 96 | /// The instance to compare with. 97 | /// True if the instances are equal; otherwise, false. 98 | public override bool Equals(object obj) 99 | { 100 | if (!(obj is ScalarValue sv)) return false; 101 | return Equals(Value, sv.Value); 102 | } 103 | 104 | /// 105 | /// Get a hash code representing the value. 106 | /// 107 | /// The instance's hash code. 108 | public override int GetHashCode() 109 | { 110 | if (Value == null) return 0; 111 | return Value.GetHashCode(); 112 | } 113 | } 114 | } -------------------------------------------------------------------------------- /test/MessageTemplates.Tests/Formatting/JsonValueFormatterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using MessageTemplates.Formatting; 5 | using MessageTemplates.Structure; 6 | using Xunit; 7 | 8 | namespace MessageTemplates.Tests.Formatting 9 | { 10 | public class JsonValueFormatterTests 11 | { 12 | class JsonLiteralValueFormatter : JsonValueFormatter 13 | { 14 | public string Format(object literal) 15 | { 16 | var output = new StringWriter(); 17 | FormatLiteralValue(literal, output); 18 | return output.ToString(); 19 | } 20 | } 21 | 22 | [Theory] 23 | [InlineData(123, "123")] 24 | [InlineData('c', "\"c\"")] 25 | [InlineData("Hello, world!", "\"Hello, world!\"")] 26 | [InlineData(true, "true")] 27 | [InlineData("\\\"\t\r\n\f", "\"\\\\\\\"\\t\\r\\n\\f\"")] 28 | [InlineData("\u0001", "\"\\u0001\"")] 29 | [InlineData("a\nb", "\"a\\nb\"")] 30 | [InlineData(null, "null")] 31 | public void JsonLiteralTypesAreFormatted(object value, string expectedJson) 32 | { 33 | var formatter = new JsonLiteralValueFormatter(); 34 | Assert.Equal(expectedJson, formatter.Format(value)); 35 | } 36 | 37 | [Fact] 38 | public void DateTimesFormatAsIso8601() 39 | { 40 | JsonLiteralTypesAreFormatted(new DateTime(2016, 01, 01, 13, 13, 13, DateTimeKind.Utc), "\"2016-01-01T13:13:13.0000000Z\""); 41 | } 42 | 43 | [Fact] 44 | public void DoubleFormatsAsNumber() 45 | { 46 | JsonLiteralTypesAreFormatted(123.45, "123.45"); 47 | } 48 | 49 | [Fact] 50 | public void DecimalFormatsAsNumber() 51 | { 52 | JsonLiteralTypesAreFormatted(123.45m, "123.45"); 53 | } 54 | 55 | static string Format(TemplatePropertyValue value) 56 | { 57 | var formatter = new JsonValueFormatter(); 58 | var output = new StringWriter(); 59 | formatter.Format(value, output); 60 | return output.ToString(); 61 | } 62 | 63 | [Fact] 64 | public void ScalarPropertiesFormatAsLiteralValues() 65 | { 66 | var f = Format(new ScalarValue(123)); 67 | Assert.Equal("123", f); 68 | } 69 | 70 | [Fact] 71 | public void SequencePropertiesFormatAsArrayValue() 72 | { 73 | var f = Format(new SequenceValue(new[] { new ScalarValue(123), new ScalarValue(456) })); 74 | Assert.Equal("[123,456]", f); 75 | } 76 | 77 | [Fact] 78 | public void StructuresFormatAsAnObject() 79 | { 80 | var structure = new StructureValue(new[] { new TemplateProperty("A", new ScalarValue(123)) }, "T"); 81 | var f = Format(structure); 82 | Assert.Equal("{\"A\":123,\"_typeTag\":\"T\"}", f); 83 | } 84 | 85 | [Fact] 86 | public void DictionaryWithScalarKeyFormatsAsAnObject() 87 | { 88 | var dict = new DictionaryValue(new Dictionary { 89 | { new ScalarValue(12), new ScalarValue(345) } 90 | }); 91 | 92 | var f = Format(dict); 93 | Assert.Equal("{\"12\":345}", f); 94 | } 95 | 96 | [Fact] 97 | public void SequencesOfSequencesAreFormatted() 98 | { 99 | var s = new SequenceValue(new[] { new SequenceValue(new[] { new ScalarValue("Hello") }) }); 100 | 101 | var f = Format(s); 102 | Assert.Equal("[[\"Hello\"]]", f); 103 | } 104 | 105 | [Fact] 106 | public void TypeTagCanBeOverridden() 107 | { 108 | var structure = new StructureValue(new TemplateProperty[0], "T"); 109 | var formatter = new JsonValueFormatter("$type"); 110 | var output = new StringWriter(); 111 | formatter.Format(structure, output); 112 | var f = output.ToString(); 113 | Assert.Equal("{\"$type\":\"T\"}", f); 114 | } 115 | 116 | [Fact] 117 | public void WhenNullNoTypeTagIsWritten() 118 | { 119 | var structure = new StructureValue(new TemplateProperty[0], "T"); 120 | var formatter = new JsonValueFormatter(null); 121 | var output = new StringWriter(); 122 | formatter.Format(structure, output); 123 | var f = output.ToString(); 124 | Assert.Equal("{}", f); 125 | } 126 | } 127 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # MessageTemplates 3 | 4 | An implementation of named string replacements, which allows formatting, parsing, and capturing properties. MessageTemplates is compatible with the [Message Templates Standard](https://messagetemplates.org/). The C# implementation was extracted from Serilog. 5 | 6 | There is also a F# implementation, see the [messagetemplates-fsharp repository](https://github.com/messagetemplates/messagetemplates-fsharp). 7 | 8 | [![Build status](https://ci.appveyor.com/api/projects/status/vqky5udqsjddgnx5/branch/master?svg=true)](https://ci.appveyor.com/project/adamchester/messagetemplates-csharp/branch/master) 9 | [![NuGet](https://img.shields.io/nuget/v/MessageTemplates.svg?maxAge=2592000)](https://www.nuget.org/packages/MessageTemplates) 10 | 11 | ### Samples 12 | 13 | ### Format a C# Class 14 | 15 | ```csharp 16 | class Chair { 17 | public string Back => "straight"; 18 | public int[] Legs => new[] {1, 2, 3, 4}; 19 | public override string ToString() => "a chair"; 20 | } 21 | 22 | Assert.Equal( 23 | "I sat at Chair { Back: \"straight\", Legs: [1, 2, 3, 4] }", 24 | MessageTemplate.Format("I sat at {@Chair}", new Chair())); 25 | ``` 26 | 27 | ### Message Template Syntax 28 | 29 | Message templates are a superset of standard .NET format strings, so any format string acceptable to `string.Format()` will also be correctly processed by `MessageTemplates`. 30 | 31 | * Property names are written between `{` and `}` brackets 32 | * Brackets can be escaped by doubling them, e.g. `{{` will be rendered as `{` 33 | * Formats that use numeric property names, like `{0}` and `{1}` exclusively, will be matched with the `Format` method's parameters by treating the property names as indexes; this is identical to `string.Format()`'s behaviour 34 | * If any of the property names are non-numeric, then all property names will be matched from left-to-right with the `Format` method's parameters 35 | * Property names may be prefixed with an optional operator, `@` or `$`, to control how the property is serialised 36 | * The destructuring operator (`@`) in front of will serialize the object passed in, rather than convert it using `ToString()`. 37 | * the stringification operator (`$`) will convert the property value to a string before any other processing takes place, regardless of its type or implemented interfaces. 38 | * Property names may be suffixed with an optional format, e.g. `:000`, to control how the property is rendered; these format strings behave exactly as their counterparts within the `string.Format()` syntax 39 | 40 | ### Compiling 41 | 42 | Install [dotnet core sdk 2.1.104](https://www.microsoft.com/net/download/dotnet-core/sdk-2.1.104) or compatible, and run `build.cmd` (windows) or `build.sh` (osx/linux). 43 | 44 | ### Rendering JSON data 45 | 46 | _MessageTemplates_ can be used for offline rendering of log data. Often this is recorded in JSON format. 47 | 48 | The example below shows how to take a message template and a JSON document, and render the template using values from the JSON. 49 | 50 | JSON.NET is used for JSON parsing; to install dependencies: 51 | 52 | ```ps 53 | Install-Package Newtonsoft.Json 54 | Install-Package MessageTemplates -Pre 55 | ``` 56 | 57 | The example program prints the results of rendering the template out to the console: 58 | 59 | ```csharp 60 | public class Program 61 | { 62 | public static void Main() 63 | { 64 | var template = "Hello {Name}; see: {Data}"; 65 | var json = @"{""Name"": ""Alice"", ""Data"": {""Counts"": [1, 2, 3]}}"; 66 | 67 | var properties = (JObject) JsonConvert.DeserializeObject(json); 68 | 69 | var parser = new MessageTemplateParser(); 70 | var parsed = parser.Parse(template); 71 | 72 | var templateProperties = new TemplatePropertyValueDictionary(new TemplatePropertyList( 73 | properties.Properties().Select(p => CreateProperty(p.Name, p.Value)).ToArray())); 74 | 75 | var rendered = parsed.Render(templateProperties); 76 | Console.WriteLine(rendered); 77 | } 78 | 79 | static TemplateProperty CreateProperty(string name, JToken value) 80 | { 81 | return new TemplateProperty(name, CreatePropertyValue(value)); 82 | } 83 | 84 | static TemplatePropertyValue CreatePropertyValue(JToken value) 85 | { 86 | if (value.Type == JTokenType.Null) 87 | return new ScalarValue(null); 88 | 89 | var obj = value as JObject; 90 | if (obj != null) 91 | { 92 | var properties = obj.Properties() 93 | .Select(kvp => CreateProperty(kvp.Name, kvp.Value)); 94 | 95 | return new StructureValue(properties); 96 | } 97 | 98 | var arr = value as JArray; 99 | if (arr != null) 100 | { 101 | return new SequenceValue(arr.Select(CreatePropertyValue)); 102 | } 103 | 104 | return new ScalarValue(value.Value()); 105 | } 106 | } 107 | ``` 108 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | [Xx]64/ 19 | [Xx]86/ 20 | [Bb]uild/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | 85 | # Visual Studio profiler 86 | *.psess 87 | *.vsp 88 | *.vspx 89 | *.sap 90 | 91 | # TFS 2012 Local Workspace 92 | $tf/ 93 | 94 | # Guidance Automation Toolkit 95 | *.gpState 96 | 97 | # ReSharper is a .NET coding add-in 98 | _ReSharper*/ 99 | *.[Rr]e[Ss]harper 100 | *.DotSettings.user 101 | 102 | # JustCode is a .NET coding add-in 103 | .JustCode 104 | 105 | # TeamCity is a build add-in 106 | _TeamCity* 107 | 108 | # DotCover is a Code Coverage Tool 109 | *.dotCover 110 | 111 | # NCrunch 112 | _NCrunch_* 113 | .*crunch*.local.xml 114 | nCrunchTemp_* 115 | 116 | # MightyMoose 117 | *.mm.* 118 | AutoTest.Net/ 119 | 120 | # Web workbench (sass) 121 | .sass-cache/ 122 | 123 | # Installshield output folder 124 | [Ee]xpress/ 125 | 126 | # DocProject is a documentation generator add-in 127 | DocProject/buildhelp/ 128 | DocProject/Help/*.HxT 129 | DocProject/Help/*.HxC 130 | DocProject/Help/*.hhc 131 | DocProject/Help/*.hhk 132 | DocProject/Help/*.hhp 133 | DocProject/Help/Html2 134 | DocProject/Help/html 135 | 136 | # Click-Once directory 137 | publish/ 138 | 139 | # Publish Web Output 140 | *.[Pp]ublish.xml 141 | *.azurePubxml 142 | 143 | # TODO: Un-comment the next line if you do not want to checkin 144 | # your web deploy settings because they may include unencrypted 145 | # passwords 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # NuGet Packages 150 | *.nupkg 151 | # The packages folder can be ignored because of Package Restore 152 | **/packages/* 153 | # except build/, which is used as an MSBuild target. 154 | !**/packages/build/ 155 | # Uncomment if necessary however generally it will be regenerated when needed 156 | #!**/packages/repositories.config 157 | # NuGet v3's project.json files produces more ignoreable files 158 | *.nuget.props 159 | *.nuget.targets 160 | 161 | # Microsoft Azure Build Output 162 | csx/ 163 | *.build.csdef 164 | 165 | # Microsoft Azure Emulator 166 | ecf/ 167 | rcf/ 168 | 169 | # Microsoft Azure ApplicationInsights config file 170 | ApplicationInsights.config 171 | 172 | # Windows Store app package directory 173 | AppPackages/ 174 | BundleArtifacts/ 175 | 176 | # Visual Studio cache files 177 | # files ending in .cache can be ignored 178 | *.[Cc]ache 179 | # but keep track of directories ending in .cache 180 | !*.[Cc]ache/ 181 | 182 | # Others 183 | ClientBin/ 184 | [Ss]tyle[Cc]op.* 185 | ~$* 186 | *~ 187 | *.dbmdl 188 | *.dbproj.schemaview 189 | *.pfx 190 | *.publishsettings 191 | node_modules/ 192 | orleans.codegen.cs 193 | 194 | # RIA/Silverlight projects 195 | Generated_Code/ 196 | 197 | # Backup & report files from converting an old project file 198 | # to a newer Visual Studio version. Backup files are not needed, 199 | # because we have git ;-) 200 | _UpgradeReport_Files/ 201 | Backup*/ 202 | UpgradeLog*.XML 203 | UpgradeLog*.htm 204 | 205 | # SQL Server files 206 | *.mdf 207 | *.ldf 208 | 209 | # Business Intelligence projects 210 | *.rdl.data 211 | *.bim.layout 212 | *.bim_*.settings 213 | 214 | # Microsoft Fakes 215 | FakesAssemblies/ 216 | 217 | # GhostDoc plugin setting file 218 | *.GhostDoc.xml 219 | 220 | # Node.js Tools for Visual Studio 221 | .ntvs_analysis.dat 222 | 223 | # Visual Studio 6 build log 224 | *.plg 225 | 226 | # Visual Studio 6 workspace options file 227 | *.opt 228 | 229 | # Visual Studio LightSwitch build output 230 | **/*.HTMLClient/GeneratedArtifacts 231 | **/*.DesktopClient/GeneratedArtifacts 232 | **/*.DesktopClient/ModelManifest.xml 233 | **/*.Server/GeneratedArtifacts 234 | **/*.Server/ModelManifest.xml 235 | _Pvt_Extensions 236 | 237 | # LightSwitch generated files 238 | GeneratedArtifacts/ 239 | ModelManifest.xml 240 | 241 | # Paket dependency manager 242 | .paket/paket.exe 243 | 244 | # FAKE - F# Make 245 | .fake/ 246 | .vscode/ 247 | -------------------------------------------------------------------------------- /src/MessageTemplates/Data/TemplatePropertyValueVisitor.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 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 System; 16 | using MessageTemplates.Structure; 17 | 18 | namespace MessageTemplates.Data 19 | { 20 | /// 21 | /// An abstract base class for visitors that walk data in the 22 | /// format. Subclasses, by 23 | /// overriding appropriate methods, may search for, transform, 24 | /// or print the value structures being visited. 25 | /// 26 | /// 27 | /// Stateless, designed to accommodate allocation-free visiting of multiple 28 | /// values by the same visitor instance. 29 | /// 30 | /// The type of a state object passed through 31 | /// the visiting process. 32 | /// The type of the result generated by visiting 33 | /// a node. 34 | public abstract class TemplatePropertyValueVisitor 35 | { 36 | /// 37 | /// Visit the root node type. This method delegates to 38 | /// a concrete Visit*Value() method appropriate for the value. 39 | /// 40 | /// Operation state. 41 | /// The value to visit. 42 | /// The result of visiting . 43 | // ReSharper disable once VirtualMemberNeverOverriden.Global 44 | protected virtual TResult Visit(TState state, TemplatePropertyValue value) 45 | { 46 | if (value == null) throw new ArgumentNullException(nameof(value)); 47 | 48 | if (value is ScalarValue sv) 49 | return VisitScalarValue(state, sv); 50 | 51 | if (value is SequenceValue seqv) 52 | return VisitSequenceValue(state, seqv); 53 | 54 | if (value is StructureValue strv) 55 | return VisitStructureValue(state, strv); 56 | 57 | if (value is DictionaryValue dictv) 58 | return VisitDictionaryValue(state, dictv); 59 | 60 | return VisitUnsupportedValue(state, value); 61 | } 62 | 63 | /// 64 | /// Visit a value. 65 | /// 66 | /// Operation state. 67 | /// The value to visit. 68 | /// The result of visiting . 69 | protected abstract TResult VisitScalarValue(TState state, ScalarValue scalar); 70 | 71 | /// 72 | /// Visit a value. 73 | /// 74 | /// Operation state. 75 | /// The value to visit. 76 | /// The result of visiting . 77 | protected abstract TResult VisitSequenceValue(TState state, SequenceValue sequence); 78 | 79 | /// 80 | /// Visit a value. 81 | /// 82 | /// Operation state. 83 | /// The value to visit. 84 | /// The result of visiting . 85 | protected abstract TResult VisitStructureValue(TState state, StructureValue structure); 86 | 87 | /// 88 | /// Visit a value. 89 | /// 90 | /// Operation state. 91 | /// The value to visit. 92 | /// The result of visiting . 93 | protected abstract TResult VisitDictionaryValue(TState state, DictionaryValue dictionary); 94 | 95 | /// 96 | /// Visit a value of an unsupported type. 97 | /// 98 | /// Operation state. 99 | /// The value to visit. 100 | /// The result of visiting . 101 | // ReSharper disable once UnusedParameter.Global 102 | // ReSharper disable once VirtualMemberNeverOverriden.Global 103 | protected virtual TResult VisitUnsupportedValue(TState state, TemplatePropertyValue value) 104 | { 105 | if (value == null) throw new ArgumentNullException(nameof(value)); 106 | throw new NotSupportedException($"The value {value} is not of a type supported by this visitor."); 107 | } 108 | } 109 | } -------------------------------------------------------------------------------- /test/MessageTemplates.Net35Tests/MessageTemplates.Net35Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Debug 7 | AnyCPU 8 | {211303BE-89AE-414B-8746-0EBDF6B2727A} 9 | Library 10 | Properties 11 | MessageTemplates.Net35Tests 12 | MessageTemplates.Net35Tests 13 | v4.5 14 | 512 15 | 16 | 17 | 18 | 19 | 20 | true 21 | full 22 | false 23 | bin\Debug\ 24 | DEBUG;TRACE 25 | prompt 26 | 4 27 | false 28 | 29 | 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | false 37 | 38 | 39 | 40 | False 41 | ..\..\src\MessageTemplates\bin\Release\net35\MessageTemplates.dll 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | ..\..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll 53 | True 54 | 55 | 56 | ..\..\packages\xunit.assert.2.1.0\lib\dotnet\xunit.assert.dll 57 | True 58 | 59 | 60 | ..\..\packages\xunit.extensibility.core.2.1.0\lib\dotnet\xunit.core.dll 61 | True 62 | 63 | 64 | ..\..\packages\xunit.extensibility.execution.2.1.0\lib\net45\xunit.execution.desktop.dll 65 | True 66 | 67 | 68 | 69 | 70 | FormatTests.cs 71 | 72 | 73 | ParserTests.cs 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 87 | 88 | 89 | 90 | 97 | -------------------------------------------------------------------------------- /test/MessageTemplates.Net40Tests/MessageTemplates.Net40Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Debug 7 | AnyCPU 8 | {481D8962-9EFD-4470-BF83-87A761581367} 9 | Library 10 | Properties 11 | MessageTemplates.Net40Tests 12 | MessageTemplates.Net40Tests 13 | v4.5 14 | 512 15 | 16 | 17 | 18 | 19 | 20 | true 21 | full 22 | false 23 | bin\Debug\ 24 | DEBUG;TRACE 25 | prompt 26 | 4 27 | false 28 | 29 | 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | false 37 | 38 | 39 | 40 | False 41 | ..\..\src\MessageTemplates\bin\Release\net40\MessageTemplates.dll 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | ..\..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll 53 | True 54 | 55 | 56 | ..\..\packages\xunit.assert.2.1.0\lib\dotnet\xunit.assert.dll 57 | True 58 | 59 | 60 | ..\..\packages\xunit.extensibility.core.2.1.0\lib\dotnet\xunit.core.dll 61 | True 62 | 63 | 64 | ..\..\packages\xunit.extensibility.execution.2.1.0\lib\net45\xunit.execution.desktop.dll 65 | True 66 | 67 | 68 | 69 | 70 | FormatTests.cs 71 | 72 | 73 | ParserTests.cs 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 87 | 88 | 89 | 90 | 97 | -------------------------------------------------------------------------------- /test/MessageTemplates.Tests/ParserTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using MessageTemplates.Parsing; 3 | using Xunit; 4 | 5 | namespace MessageTemplates.Tests 6 | { 7 | public class ParserTests 8 | { 9 | static MessageTemplateToken[] Parse(string messsageTemplate) 10 | { 11 | return new MessageTemplateParser().Parse(messsageTemplate).Tokens.ToArray(); 12 | } 13 | 14 | static void AssertParsedAs(string message, params MessageTemplateToken[] messageTemplateTokens) 15 | { 16 | var parsed = Parse(message); 17 | Assert.Equal( 18 | parsed, 19 | messageTemplateTokens); 20 | } 21 | 22 | [Fact] 23 | public void AnEmptyMessageIsASingleTextToken() 24 | { 25 | var t = Parse(""); 26 | Assert.Single(t); 27 | Assert.IsType(t.Single()); 28 | } 29 | 30 | [Fact] 31 | public void AMessageWithoutPropertiesIsASingleTextToken() 32 | { 33 | AssertParsedAs("Hello, world!", 34 | new TextToken("Hello, world!")); 35 | } 36 | 37 | [Fact] 38 | public void AMessageWithPropertyOnlyIsASinglePropertyToken() 39 | { 40 | AssertParsedAs("{Hello}", 41 | new PropertyToken("Hello", "{Hello}")); 42 | } 43 | 44 | [Fact] 45 | public void DoubledLeftBracketsAreParsedAsASingleBracket() 46 | { 47 | AssertParsedAs("{{ Hi! }", 48 | new TextToken("{ Hi! }")); 49 | } 50 | 51 | [Fact] 52 | public void DoubledLeftBracketsAreParsedAsASingleBracketInsideText() 53 | { 54 | AssertParsedAs("Well, {{ Hi!", 55 | new TextToken("Well, { Hi!")); 56 | } 57 | 58 | [Fact] 59 | public void DoubledRightBracketsAreParsedAsASingleBracket() 60 | { 61 | AssertParsedAs("Nice }}-: mo", 62 | new TextToken("Nice }-: mo")); 63 | } 64 | 65 | [Fact] 66 | public void AMalformedPropertyTagIsParsedAsText() 67 | { 68 | AssertParsedAs("{0 space}", 69 | new TextToken("{0 space}")); 70 | } 71 | 72 | [Fact] 73 | public void AnIntegerPropertyNameIsParsedAsPositionalProperty() 74 | { 75 | var parsed = (PropertyToken)Parse("{0}").Single(); 76 | Assert.Equal("0", parsed.PropertyName); 77 | Assert.True(parsed.IsPositional); 78 | } 79 | 80 | [Fact] 81 | public void FormatsCanContainColons() 82 | { 83 | var parsed = (PropertyToken)Parse("{Time:hh:mm}").Single(); 84 | Assert.Equal("hh:mm", parsed.Format); 85 | } 86 | 87 | [Fact] 88 | public void ZeroValuesAlignmentIsParsedAsText() 89 | { 90 | AssertParsedAs("{Hello,-0}", 91 | new TextToken("{Hello,-0}")); 92 | 93 | AssertParsedAs("{Hello,0}", 94 | new TextToken("{Hello,0}")); 95 | } 96 | 97 | [Fact] 98 | public void NonNumberAlignmentIsParsedAsText() 99 | { 100 | AssertParsedAs("{Hello,-aa}", 101 | new TextToken("{Hello,-aa}")); 102 | 103 | AssertParsedAs("{Hello,aa}", 104 | new TextToken("{Hello,aa}")); 105 | 106 | AssertParsedAs("{Hello,-10-1}", 107 | new TextToken("{Hello,-10-1}")); 108 | 109 | AssertParsedAs("{Hello,10-1}", 110 | new TextToken("{Hello,10-1}")); 111 | } 112 | 113 | [Fact] 114 | public void EmptyAlignmentIsParsedAsText() 115 | { 116 | AssertParsedAs("{Hello,}", 117 | new TextToken("{Hello,}")); 118 | 119 | AssertParsedAs("{Hello,:format}", 120 | new TextToken("{Hello,:format}")); 121 | } 122 | 123 | [Fact] 124 | public void MultipleTokensHasCorrectIndexes() 125 | { 126 | AssertParsedAs("{Greeting}, {Name}!", 127 | new PropertyToken("Greeting", "{Greeting}"), 128 | new TextToken(", ", 10), 129 | new PropertyToken("Name", "{Name}", startIndex: 12), 130 | new TextToken("!", 18)); 131 | } 132 | 133 | [Fact] 134 | public void MissingRightBracketIsParsedAsText() 135 | { 136 | AssertParsedAs("{Hello", 137 | new TextToken("{Hello")); 138 | } 139 | 140 | [Fact] 141 | public void DestructureHintIsParsedCorrectly() 142 | { 143 | var parsed = (PropertyToken)Parse("{@Hello}").Single(); 144 | Assert.Equal(Destructuring.Destructure, parsed.Destructuring); 145 | } 146 | 147 | [Fact] 148 | public void StringifyHintIsParsedCorrectly() 149 | { 150 | var parsed = (PropertyToken)Parse("{$Hello}").Single(); 151 | Assert.Equal(Destructuring.Stringify, parsed.Destructuring); 152 | } 153 | 154 | [Fact] 155 | public void DestructuringWithEmptyPropertyNameIsParsedAsText() 156 | { 157 | AssertParsedAs("{@}", 158 | new TextToken("{@}")); 159 | } 160 | 161 | [Fact] 162 | public void UnderscoresAreValidInPropertyNames() 163 | { 164 | AssertParsedAs("{_123_Hello}", new PropertyToken("_123_Hello", "{_123_Hello}")); 165 | } 166 | 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /src/MessageTemplates/Parameters/PropertyBinder.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 System; 16 | using MessageTemplates.Core; 17 | using MessageTemplates.Debugging; 18 | using MessageTemplates.Parsing; 19 | using MessageTemplates.Structure; 20 | 21 | namespace MessageTemplates.Parameters 22 | { 23 | // Performance relevant - on the hot path when creating log events from existing templates. 24 | class PropertyBinder 25 | { 26 | readonly PropertyValueConverter _valueConverter; 27 | 28 | static readonly TemplateProperty[] NoPropertiesArray = new TemplateProperty[0]; 29 | static readonly TemplatePropertyList NoProperties = new TemplatePropertyList(NoPropertiesArray); 30 | 31 | public PropertyBinder(PropertyValueConverter valueConverter) 32 | { 33 | _valueConverter = valueConverter; 34 | } 35 | 36 | /// 37 | /// Create properties based on an ordered list of provided values. 38 | /// 39 | /// The template that the parameters apply to. 40 | /// Objects corresponding to the properties 41 | /// represented in the message template. 42 | /// A list of properties; if the template is malformed then 43 | /// this will be empty. 44 | public TemplatePropertyList ConstructProperties(MessageTemplate messageTemplate, object[] messageTemplateParameters) 45 | { 46 | if (messageTemplateParameters == null || messageTemplateParameters.Length == 0) 47 | { 48 | if (messageTemplate.NamedProperties != null || messageTemplate.PositionalProperties != null) 49 | SelfLog.WriteLine("Required properties not provided for: {0}", messageTemplate); 50 | 51 | return NoProperties; 52 | } 53 | 54 | if (messageTemplate.PositionalProperties != null) 55 | return ConstructPositionalProperties(messageTemplate, messageTemplateParameters); 56 | 57 | return ConstructNamedProperties(messageTemplate, messageTemplateParameters); 58 | } 59 | 60 | TemplatePropertyList ConstructPositionalProperties(MessageTemplate template, object[] messageTemplateParameters) 61 | { 62 | var positionalProperties = template.PositionalProperties; 63 | 64 | if (positionalProperties.Length != messageTemplateParameters.Length) 65 | SelfLog.WriteLine("Positional property count does not match parameter count: {0}", template); 66 | 67 | var result = new TemplateProperty[messageTemplateParameters.Length]; 68 | foreach (var property in positionalProperties) 69 | { 70 | if (property.TryGetPositionalValue(out var position)) 71 | { 72 | if (position < 0 || position >= messageTemplateParameters.Length) 73 | SelfLog.WriteLine("Unassigned positional value {0} in: {1}", position, template); 74 | else 75 | result[position] = ConstructProperty(property, messageTemplateParameters[position]); 76 | } 77 | } 78 | 79 | var next = 0; 80 | for (var i = 0; i < result.Length; ++i) 81 | { 82 | if (result[i] != null) 83 | { 84 | result[next] = result[i]; 85 | ++next; 86 | } 87 | } 88 | 89 | if (next != result.Length) 90 | Array.Resize(ref result, next); 91 | 92 | return new TemplatePropertyList(result); 93 | } 94 | 95 | TemplatePropertyList ConstructNamedProperties(MessageTemplate template, object[] messageTemplateParameters) 96 | { 97 | var namedProperties = template.NamedProperties; 98 | if (namedProperties == null) 99 | return NoProperties; 100 | 101 | var matchedRun = namedProperties.Length; 102 | if (namedProperties.Length != messageTemplateParameters.Length) 103 | { 104 | matchedRun = Math.Min(namedProperties.Length, messageTemplateParameters.Length); 105 | SelfLog.WriteLine("Named property count does not match parameter count: {0}", template); 106 | } 107 | 108 | var result = new TemplateProperty[matchedRun]; 109 | for (var i = 0; i < matchedRun; ++i) 110 | { 111 | var property = template.NamedProperties[i]; 112 | var value = messageTemplateParameters[i]; 113 | result[i] = ConstructProperty(property, value); 114 | } 115 | 116 | return new TemplatePropertyList(result); 117 | } 118 | 119 | TemplateProperty ConstructProperty(PropertyToken propertyToken, object value) 120 | { 121 | return new TemplateProperty( 122 | propertyToken.PropertyName, 123 | _valueConverter.CreatePropertyValue(value, propertyToken.Destructuring)); 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /test/MessageTemplates.Tests/FormatTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using Xunit; 4 | 5 | namespace MessageTemplates.Tests 6 | { 7 | public class FormatTests 8 | { 9 | class Chair 10 | { 11 | // ReSharper disable UnusedMember.Local 12 | public string Back { get { return "straight"; } } 13 | public int[] Legs { get { return new[] { 1, 2, 3, 4 }; } } 14 | // ReSharper restore UnusedMember.Local 15 | public override string ToString() 16 | { 17 | return "a chair"; 18 | } 19 | } 20 | 21 | class Receipt 22 | { 23 | // ReSharper disable UnusedMember.Local 24 | public decimal Sum { get { return 12.345m; } } 25 | public DateTime When { get { return new DateTime(2013, 5, 20, 16, 39, 0); } } 26 | // ReSharper restore UnusedMember.Local 27 | public override string ToString() 28 | { 29 | return "a receipt"; 30 | } 31 | } 32 | 33 | [Fact] 34 | public void AnObjectIsRenderedInSimpleNotation() 35 | { 36 | var m = Render("I sat at {@Chair}", new Chair()); 37 | Assert.Equal("I sat at Chair { Back: \"straight\", Legs: [1, 2, 3, 4] }", m); 38 | } 39 | 40 | [Fact] 41 | public void AnObjectIsRenderedInSimpleNotationUsingFormatProvider() 42 | { 43 | var m = Render(new CultureInfo("fr-FR"), "I received {@Receipt}", new Receipt()); 44 | Assert.Equal("I received Receipt { Sum: 12,345, When: 20/05/2013 16:39:00 }", m); 45 | } 46 | 47 | [Fact] 48 | public void AnAnonymousObjectIsRenderedInSimpleNotationWithoutType() 49 | { 50 | var m = Render("I sat at {@Chair}", new { Back = "straight", Legs = new[] { 1, 2, 3, 4 } }); 51 | Assert.Equal("I sat at { Back: \"straight\", Legs: [1, 2, 3, 4] }", m); 52 | } 53 | 54 | [Fact] 55 | public void AnAnonymousObjectIsRenderedInSimpleNotationWithoutTypeUsingFormatProvider() 56 | { 57 | var m = Render(new CultureInfo("fr-FR"), "I received {@Receipt}", new { Sum = 12.345, When = new DateTime(2013, 5, 20, 16, 39, 0) }); 58 | Assert.Equal("I received { Sum: 12,345, When: 20/05/2013 16:39:00 }", m); 59 | } 60 | 61 | [Fact] 62 | public void AnObjectWithDefaultDestructuringIsRenderedAsAStringLiteral() 63 | { 64 | var m = Render("I sat at {Chair}", new Chair()); 65 | Assert.Equal("I sat at \"a chair\"", m); 66 | } 67 | 68 | [Fact] 69 | public void AnObjectWithStringifyDestructuringIsRenderedAsAString() 70 | { 71 | var m = Render("I sat at {$Chair}", new Chair()); 72 | Assert.Equal("I sat at \"a chair\"", m); 73 | } 74 | 75 | [Fact] 76 | public void MultiplePropertiesAreRenderedInOrder() 77 | { 78 | var m = Render("Just biting {Fruit} number {Count}", "Apple", 12); 79 | Assert.Equal("Just biting \"Apple\" number 12", m); 80 | } 81 | 82 | [Fact] 83 | public void MultiplePropertiesUseFormatProvider() 84 | { 85 | var m = Render(new CultureInfo("fr-FR"), "Income was {Income} at {Date:d}", 1234.567, new DateTime(2013, 5, 20)); 86 | Assert.Equal("Income was 1234,567 at 20/05/2013", m); 87 | } 88 | 89 | [Fact] 90 | public void FormatStringsArePropagated() 91 | { 92 | var m = Render("Welcome, customer {CustomerId:0000}", 12); 93 | Assert.Equal("Welcome, customer 0012", m); 94 | } 95 | 96 | [Theory] 97 | [InlineData("Welcome, customer #{CustomerId,-10}, pleasure to see you", "Welcome, customer #1234 , pleasure to see you")] 98 | [InlineData("Welcome, customer #{CustomerId,-10:000000}, pleasure to see you", "Welcome, customer #001234 , pleasure to see you")] 99 | [InlineData("Welcome, customer #{CustomerId,10}, pleasure to see you", "Welcome, customer # 1234, pleasure to see you")] 100 | [InlineData("Welcome, customer #{CustomerId,10:000000}, pleasure to see you", "Welcome, customer # 001234, pleasure to see you")] 101 | [InlineData("Welcome, customer #{CustomerId,10:0,0}, pleasure to see you", "Welcome, customer # 1,234, pleasure to see you")] 102 | [InlineData("Welcome, customer #{CustomerId:0,0}, pleasure to see you", "Welcome, customer #1,234, pleasure to see you")] 103 | public void AlignmentStringsArePropagated(string value, string expected) 104 | { 105 | Assert.Equal(expected, Render(value, 1234)); 106 | } 107 | 108 | [Fact] 109 | public void FormatProviderIsUsed() 110 | { 111 | var m = Render(new CultureInfo("fr-FR"), "Please pay {Sum}", 12.345); 112 | Assert.Equal("Please pay 12,345", m); 113 | } 114 | 115 | static string Render(string messageTemplate, params object[] properties) 116 | { 117 | return Render(null, messageTemplate, properties); 118 | } 119 | 120 | static string Render(IFormatProvider formatProvider, 121 | string messageTemplate, params object[] properties) 122 | { 123 | return MessageTemplate.Format(formatProvider, messageTemplate, properties); 124 | } 125 | 126 | [Fact] 127 | public void ATemplateWithOnlyPositionalPropertiesIsAnalyzedAndRenderedPositionally() 128 | { 129 | var m = Render("{1}, {0}", "world", "Hello"); 130 | Assert.Equal("\"Hello\", \"world\"", m); 131 | } 132 | 133 | [Fact] 134 | public void ATemplateWithOnlyPositionalPropertiesUsesFormatProvider() 135 | { 136 | var m = Render(new CultureInfo("fr-FR"), "{1}, {0}", 12.345, "Hello"); 137 | Assert.Equal("\"Hello\", 12,345", m); 138 | } 139 | 140 | // Debatable what the behavior should be, here. 141 | [Fact] 142 | public void ATemplateWithNamesAndPositionalsUsesNamesForAllValues() 143 | { 144 | var m = Render("{1}, {Place}", "world", "Hello"); 145 | Assert.Equal("\"world\", \"Hello\"", m); 146 | } 147 | 148 | [Fact] 149 | public void MissingPositionalParametersRenderAsTextLikeStandardFormats() 150 | { 151 | var m = Render("{1}, {0}", "world"); 152 | Assert.Equal("{1}, \"world\"", m); 153 | } 154 | 155 | enum Size 156 | { 157 | Large 158 | } 159 | 160 | class SizeFormatter : IFormatProvider, ICustomFormatter 161 | { 162 | private readonly IFormatProvider _innerFormatProvider; 163 | 164 | public SizeFormatter(IFormatProvider innerFormatProvider) 165 | { 166 | _innerFormatProvider = innerFormatProvider; 167 | } 168 | 169 | public object GetFormat(Type formatType) 170 | { 171 | return formatType == typeof(ICustomFormatter) ? this : _innerFormatProvider.GetFormat(formatType); 172 | } 173 | 174 | public string Format(string format, object arg, IFormatProvider formatProvider) 175 | { 176 | if (arg is Size size) 177 | { 178 | return size == Size.Large ? "Huge" : size.ToString(); 179 | } 180 | 181 | if (arg is IFormattable formattable) 182 | { 183 | return formattable.ToString(format, _innerFormatProvider); 184 | } 185 | 186 | return arg.ToString(); 187 | } 188 | } 189 | 190 | [Fact] 191 | public void AppliesCustomFormatterToEnums() 192 | { 193 | var rendered = Render(new SizeFormatter(CultureInfo.InvariantCulture), "Size {size}", Size.Large); 194 | Assert.Equal("Size Huge", rendered); 195 | } 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /src/MessageTemplates/Parsing/PropertyToken.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 System; 16 | using System.ComponentModel; 17 | using System.Globalization; 18 | using System.IO; 19 | using MessageTemplates.Core; 20 | using MessageTemplates.Formatting.Display; 21 | using MessageTemplates.Structure; 22 | 23 | namespace MessageTemplates.Parsing 24 | { 25 | /// 26 | /// A message template token representing a log event property. 27 | /// 28 | public class PropertyToken : MessageTemplateToken 29 | { 30 | readonly string _rawText; 31 | readonly int? _position; 32 | 33 | /// 34 | /// Construct a . 35 | /// 36 | /// The name of the property. 37 | /// The token as it appears in the message template. 38 | /// The format applied to the property, if any. 39 | /// The destructuring strategy applied to the property, if any. 40 | /// 41 | [Obsolete("Use named arguments with this method to guarantee forwards-compatibility."), EditorBrowsable(EditorBrowsableState.Never)] 42 | public PropertyToken(string propertyName, string rawText, string formatObsolete, Destructuring destructuringObsolete) 43 | : this(propertyName, rawText, formatObsolete, null, destructuringObsolete) 44 | { 45 | } 46 | 47 | /// 48 | /// Construct a . 49 | /// 50 | /// The name of the property. 51 | /// The token as it appears in the message template. 52 | /// The format applied to the property, if any. 53 | /// The alignment applied to the property, if any. 54 | /// The destructuring strategy applied to the property, if any. 55 | /// The token's start index in the template. 56 | /// 57 | public PropertyToken(string propertyName, string rawText, string format = null, Alignment? alignment = null, Destructuring destructuring = Destructuring.Default, int startIndex = -1) 58 | : base(startIndex) 59 | { 60 | if (propertyName == null) throw new ArgumentNullException(nameof(propertyName)); 61 | if (rawText == null) throw new ArgumentNullException(nameof(rawText)); 62 | PropertyName = propertyName; 63 | Format = format; 64 | Destructuring = destructuring; 65 | _rawText = rawText; 66 | Alignment = alignment; 67 | 68 | if (int.TryParse(PropertyName, NumberStyles.None, CultureInfo.InvariantCulture, out var position) && 69 | position >= 0) 70 | { 71 | _position = position; 72 | } 73 | } 74 | 75 | /// 76 | /// The token's length. 77 | /// 78 | public override int Length => _rawText.Length; 79 | 80 | /// 81 | /// Render the token to the output. 82 | /// 83 | /// Properties that may be represented by the token. 84 | /// Output for the rendered string. 85 | /// Supplies culture-specific formatting information, or null. 86 | public override void Render(TemplatePropertyValueDictionary properties, TextWriter output, IFormatProvider formatProvider = null) 87 | { 88 | if (properties == null) throw new ArgumentNullException(nameof(properties)); 89 | if (output == null) throw new ArgumentNullException(nameof(output)); 90 | 91 | if (!properties.TryGetValue(PropertyName, out var propertyValue)) 92 | { 93 | output.Write(_rawText); 94 | return; 95 | } 96 | 97 | if (!Alignment.HasValue) 98 | { 99 | propertyValue.Render(output, Format, formatProvider); 100 | return; 101 | } 102 | 103 | var valueOutput = new StringWriter(); 104 | propertyValue.Render(valueOutput, Format, formatProvider); 105 | var value = valueOutput.ToString(); 106 | 107 | if (value.Length >= Alignment.Value.Width) 108 | { 109 | output.Write(value); 110 | return; 111 | } 112 | 113 | Padding.Apply(output, value, Alignment.Value); 114 | } 115 | 116 | /// 117 | /// The property name. 118 | /// 119 | public string PropertyName { get; } 120 | 121 | /// 122 | /// Destructuring strategy applied to the property. 123 | /// 124 | public Destructuring Destructuring { get; } 125 | 126 | /// 127 | /// Format applied to the property. 128 | /// 129 | public string Format { get; } 130 | 131 | /// 132 | /// Alignment applied to the property. 133 | /// 134 | public Alignment? Alignment { get; } 135 | 136 | /// 137 | /// True if the property name is a positional index; otherwise, false. 138 | /// 139 | public bool IsPositional => _position.HasValue; 140 | 141 | /// 142 | /// Try to get the integer value represented by the property name. 143 | /// 144 | /// The integer value, if present. 145 | /// True if the property is positional, otherwise false. 146 | public bool TryGetPositionalValue(out int position) 147 | { 148 | if (_position == null) 149 | { 150 | position = 0; 151 | return false; 152 | } 153 | 154 | position = _position.Value; 155 | return true; 156 | } 157 | 158 | /// 159 | /// Determines whether the specified is equal to the current . 160 | /// 161 | /// 162 | /// true if the specified object is equal to the current object; otherwise, false. 163 | /// 164 | /// The object to compare with the current object. 2 165 | public override bool Equals(object obj) 166 | { 167 | return obj is PropertyToken pt && 168 | pt.Destructuring == Destructuring && 169 | pt.Format == Format && 170 | pt.PropertyName == PropertyName && 171 | pt._rawText == _rawText; 172 | } 173 | 174 | /// 175 | /// Serves as a hash function for a particular type. 176 | /// 177 | /// 178 | /// A hash code for the current . 179 | /// 180 | /// 2 181 | public override int GetHashCode() => PropertyName.GetHashCode(); 182 | 183 | /// 184 | /// Returns a string that represents the current object. 185 | /// 186 | /// 187 | /// A string that represents the current object. 188 | /// 189 | /// 2 190 | public override string ToString() => _rawText; 191 | } 192 | } -------------------------------------------------------------------------------- /src/MessageTemplates/MessageTemplate.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 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 System; 16 | using System.Collections.Generic; 17 | using System.IO; 18 | using System.Linq; 19 | using MessageTemplates.Debugging; 20 | using MessageTemplates.Parsing; 21 | using System.Globalization; 22 | using MessageTemplates.Core; 23 | 24 | namespace MessageTemplates 25 | { 26 | /// 27 | /// Represents a message template passed to a log method. The template 28 | /// can subsequently render the template in textual form given the list 29 | /// of properties. 30 | /// 31 | public class MessageTemplate 32 | { 33 | readonly string _text; 34 | readonly MessageTemplateToken[] _tokens; 35 | 36 | // Optimisation for when the template is bound to 37 | // property values. 38 | readonly PropertyToken[] _positionalProperties; 39 | readonly PropertyToken[] _namedProperties; 40 | 41 | /// 42 | /// Construct a message template using manually-defined text and property tokens. 43 | /// 44 | /// The full text of the template; used by MessageTemplates internally to avoid unneeded 45 | /// string concatenation. 46 | /// The text and property tokens defining the template. 47 | public MessageTemplate(string text, IEnumerable tokens) 48 | { 49 | if (text == null) throw new ArgumentNullException(nameof(text)); 50 | if (tokens == null) throw new ArgumentNullException(nameof(tokens)); 51 | 52 | _text = text; 53 | _tokens = tokens.ToArray(); 54 | 55 | var propertyTokens = _tokens.OfType().ToArray(); 56 | if (propertyTokens.Length != 0) 57 | { 58 | var allPositional = true; 59 | var anyPositional = false; 60 | foreach (var propertyToken in propertyTokens) 61 | { 62 | if (propertyToken.IsPositional) 63 | anyPositional = true; 64 | else 65 | allPositional = false; 66 | } 67 | 68 | if (allPositional) 69 | { 70 | _positionalProperties = propertyTokens; 71 | } 72 | else 73 | { 74 | if (anyPositional) 75 | SelfLog.WriteLine("Message template is malformed: {0}", text); 76 | 77 | _namedProperties = propertyTokens; 78 | } 79 | } 80 | } 81 | 82 | /// 83 | /// The raw text describing the template. 84 | /// 85 | public string Text 86 | { 87 | get { return _text; } 88 | } 89 | 90 | /// 91 | /// Render the template as a string. 92 | /// 93 | /// The string representation of the template. 94 | public override string ToString() 95 | { 96 | return Text; 97 | } 98 | 99 | /// 100 | /// The tokens parsed from the template. 101 | /// 102 | public IEnumerable Tokens => _tokens; 103 | 104 | internal PropertyToken[] NamedProperties => _namedProperties; 105 | 106 | internal PropertyToken[] PositionalProperties => _positionalProperties; 107 | 108 | /// 109 | /// Convert the message template into a textual message, given the 110 | /// properties matching the tokens in the message template. 111 | /// 112 | /// Properties matching template tokens. 113 | /// Supplies culture-specific formatting information, or null. 114 | /// The message created from the template and properties. If the 115 | /// properties are mismatched with the template, the template will be 116 | /// returned with incomplete substitution. 117 | public string Render(TemplatePropertyValueDictionary properties, IFormatProvider formatProvider = null) 118 | { 119 | var writer = new StringWriter(formatProvider); 120 | Render(properties, writer, formatProvider); 121 | return writer.ToString(); 122 | } 123 | 124 | /// 125 | /// Convert the message template into a textual message, given the 126 | /// properties matching the tokens in the message template. 127 | /// 128 | /// Properties matching template tokens. 129 | /// The message created from the template and properties. If the 130 | /// properties are mismatched with the template, the template will be 131 | /// returned with incomplete substitution. 132 | /// Supplies culture-specific formatting information, or null. 133 | public void Render(TemplatePropertyValueDictionary properties, TextWriter output, IFormatProvider formatProvider = null) 134 | { 135 | foreach (var token in _tokens) 136 | { 137 | token.Render(properties, output, formatProvider); 138 | } 139 | } 140 | 141 | /// 142 | /// Parses a message template (e.g. "hello, {name}") into a 143 | /// structure. 144 | /// 145 | /// A message template (e.g. "hello, {name}") 146 | /// The parsed message template. 147 | public static MessageTemplate Parse(string templateMessage) 148 | { 149 | return new MessageTemplateParser().Parse(templateMessage); 150 | } 151 | 152 | /// 153 | /// Render 154 | /// 155 | public void Format(IFormatProvider formatProvider, TextWriter output, params object[] values) 156 | { 157 | var props = Capture(this, values); 158 | this.Render(new TemplatePropertyValueDictionary(props), output, formatProvider); 159 | } 160 | 161 | /// 162 | /// Render 163 | /// 164 | public string Format(IFormatProvider formatProvider, params object[] values) 165 | { 166 | var sw = new StringWriter(formatProvider); 167 | Format(formatProvider, sw, values); 168 | sw.Flush(); 169 | return sw.ToString(); 170 | } 171 | 172 | /// 173 | /// Captures properties from the given template message and the provided values. 174 | /// 175 | public static TemplatePropertyList Capture( 176 | string templateMessage, params object[] values) 177 | { 178 | var template = Parse(templateMessage); 179 | return Capture(template, values); 180 | } 181 | 182 | /// 183 | /// Captures properties from the given message template and 184 | /// provided values. 185 | /// 186 | public static TemplatePropertyList CaptureWith( 187 | int maximumDepth, IEnumerable additionalScalarTypes, 188 | IEnumerable additionalDestructuringPolicies, 189 | MessageTemplate template, params object[] values) 190 | { 191 | var binder = new Parameters.PropertyBinder( 192 | new Parameters.PropertyValueConverter( 193 | maximumDepth, 194 | additionalScalarTypes ?? Enumerable.Empty(), 195 | additionalDestructuringPolicies ?? Enumerable.Empty())); 196 | 197 | return binder.ConstructProperties(template, values); 198 | } 199 | 200 | /// 201 | /// Captures properties from the given message template and 202 | /// provided values. 203 | /// 204 | public static TemplatePropertyList Capture( 205 | MessageTemplate template, params object[] values) 206 | { 207 | var binder = new Parameters.PropertyBinder( 208 | new Parameters.PropertyValueConverter( 209 | 10, 210 | Enumerable.Empty(), 211 | Enumerable.Empty())); 212 | 213 | return binder.ConstructProperties(template, values); 214 | } 215 | 216 | /// 217 | /// Formats the message template as a string, written into the text 218 | /// writer. 219 | /// 220 | public static void Format( 221 | IFormatProvider formatProvider, 222 | TextWriter output, 223 | string templateMessage, 224 | params object[] values) 225 | { 226 | var template = Parse(templateMessage); 227 | template.Format(formatProvider, output, values); 228 | } 229 | 230 | /// 231 | /// Formats the message template as a string using the provided 232 | /// format provider and values. 233 | /// 234 | public static string Format( 235 | IFormatProvider formatProvider, 236 | string templateMessage, 237 | params object[] values) 238 | { 239 | var sw = new StringWriter(formatProvider); 240 | Format(formatProvider, sw, templateMessage, values); 241 | sw.Flush(); 242 | return sw.ToString(); 243 | } 244 | 245 | /// 246 | /// Formats the message template as a string using the provided values. 247 | /// 248 | public static string Format( 249 | string templateMessage, 250 | params object[] values) 251 | { 252 | return Format(CultureInfo.InvariantCulture, templateMessage, values); 253 | } 254 | } 255 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct or 18 | indirect, to cause the direction or management of such entity, whether by 19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising 23 | permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation or 30 | translation of a Source form, including but not limited to compiled object code, 31 | generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, made 34 | available under the License, as indicated by a copyright notice that is included 35 | in or attached to the work (an example is provided in the Appendix below). 36 | 37 | "Derivative Works" shall mean any work, whether in Source or Object form, that 38 | is based on (or derived from) the Work and for which the editorial revisions, 39 | annotations, elaborations, or other modifications represent, as a whole, an 40 | original work of authorship. For the purposes of this License, Derivative Works 41 | shall not include works that remain separable from, or merely link (or bind by 42 | name) to the interfaces of, the Work and Derivative Works thereof. 43 | 44 | "Contribution" shall mean any work of authorship, including the original version 45 | of the Work and any modifications or additions to that Work or Derivative Works 46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 47 | by the copyright owner or by an individual or Legal Entity authorized to submit 48 | on behalf of the copyright owner. For the purposes of this definition, 49 | "submitted" means any form of electronic, verbal, or written communication sent 50 | to the Licensor or its representatives, including but not limited to 51 | communication on electronic mailing lists, source code control systems, and 52 | issue tracking systems that are managed by, or on behalf of, the Licensor for 53 | the purpose of discussing and improving the Work, but excluding communication 54 | that is conspicuously marked or otherwise designated in writing by the copyright 55 | owner as "Not a Contribution." 56 | 57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 58 | of whom a Contribution has been received by Licensor and subsequently 59 | incorporated within the Work. 60 | 61 | 2. Grant of Copyright License. 62 | 63 | Subject to the terms and conditions of this License, each Contributor hereby 64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 65 | irrevocable copyright license to reproduce, prepare Derivative Works of, 66 | publicly display, publicly perform, sublicense, and distribute the Work and such 67 | Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. 70 | 71 | Subject to the terms and conditions of this License, each Contributor hereby 72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 73 | irrevocable (except as stated in this section) patent license to make, have 74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 75 | such license applies only to those patent claims licensable by such Contributor 76 | that are necessarily infringed by their Contribution(s) alone or by combination 77 | of their Contribution(s) with the Work to which such Contribution(s) was 78 | submitted. If You institute patent litigation against any entity (including a 79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 80 | Contribution incorporated within the Work constitutes direct or contributory 81 | patent infringement, then any patent licenses granted to You under this License 82 | for that Work shall terminate as of the date such litigation is filed. 83 | 84 | 4. Redistribution. 85 | 86 | You may reproduce and distribute copies of the Work or Derivative Works thereof 87 | in any medium, with or without modifications, and in Source or Object form, 88 | provided that You meet the following conditions: 89 | 90 | You must give any other recipients of the Work or Derivative Works a copy of 91 | this License; and 92 | You must cause any modified files to carry prominent notices stating that You 93 | changed the files; and 94 | You must retain, in the Source form of any Derivative Works that You distribute, 95 | all copyright, patent, trademark, and attribution notices from the Source form 96 | of the Work, excluding those notices that do not pertain to any part of the 97 | Derivative Works; and 98 | If the Work includes a "NOTICE" text file as part of its distribution, then any 99 | Derivative Works that You distribute must include a readable copy of the 100 | attribution notices contained within such NOTICE file, excluding those notices 101 | that do not pertain to any part of the Derivative Works, in at least one of the 102 | following places: within a NOTICE text file distributed as part of the 103 | Derivative Works; within the Source form or documentation, if provided along 104 | with the Derivative Works; or, within a display generated by the Derivative 105 | Works, if and wherever such third-party notices normally appear. The contents of 106 | the NOTICE file are for informational purposes only and do not modify the 107 | License. You may add Your own attribution notices within Derivative Works that 108 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 109 | provided that such additional attribution notices cannot be construed as 110 | modifying the License. 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, or 113 | distribution of Your modifications, or for any such Derivative Works as a whole, 114 | provided Your use, reproduction, and distribution of the Work otherwise complies 115 | with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. 118 | 119 | Unless You explicitly state otherwise, any Contribution intentionally submitted 120 | for inclusion in the Work by You to the Licensor shall be under the terms and 121 | conditions of this License, without any additional terms or conditions. 122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 123 | any separate license agreement you may have executed with Licensor regarding 124 | such Contributions. 125 | 126 | 6. Trademarks. 127 | 128 | This License does not grant permission to use the trade names, trademarks, 129 | service marks, or product names of the Licensor, except as required for 130 | reasonable and customary use in describing the origin of the Work and 131 | reproducing the content of the NOTICE file. 132 | 133 | 7. Disclaimer of Warranty. 134 | 135 | Unless required by applicable law or agreed to in writing, Licensor provides the 136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 138 | including, without limitation, any warranties or conditions of TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 140 | solely responsible for determining the appropriateness of using or 141 | redistributing the Work and assume any risks associated with Your exercise of 142 | permissions under this License. 143 | 144 | 8. Limitation of Liability. 145 | 146 | In no event and under no legal theory, whether in tort (including negligence), 147 | contract, or otherwise, unless required by applicable law (such as deliberate 148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 149 | liable to You for damages, including any direct, indirect, special, incidental, 150 | or consequential damages of any character arising as a result of this License or 151 | out of the use or inability to use the Work (including but not limited to 152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 153 | any and all other commercial damages or losses), even if such Contributor has 154 | been advised of the possibility of such damages. 155 | 156 | 9. Accepting Warranty or Additional Liability. 157 | 158 | While redistributing the Work or Derivative Works thereof, You may choose to 159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 160 | other liability obligations and/or rights consistent with this License. However, 161 | in accepting such obligations, You may act only on Your own behalf and on Your 162 | sole responsibility, not on behalf of any other Contributor, and only if You 163 | agree to indemnify, defend, and hold each Contributor harmless for any liability 164 | incurred by, or claims asserted against, such Contributor by reason of your 165 | accepting any such warranty or additional liability. 166 | 167 | END OF TERMS AND CONDITIONS 168 | 169 | APPENDIX: How to apply the Apache License to your work 170 | 171 | To apply the Apache License to your work, attach the following boilerplate 172 | notice, with the fields enclosed by brackets "[]" replaced with your own 173 | identifying information. (Don't include the brackets!) The text should be 174 | enclosed in the appropriate comment syntax for the file format. We also 175 | recommend that a file or class name and description of purpose be included on 176 | the same "printed page" as the copyright notice for easier identification within 177 | third-party archives. 178 | 179 | Copyright [yyyy] [name of copyright owner] 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. 192 | -------------------------------------------------------------------------------- /src/MessageTemplates/Parsing/MessageTemplateParser.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 System; 16 | using System.Collections.Generic; 17 | using System.Text; 18 | using MessageTemplates.Core; 19 | 20 | namespace MessageTemplates.Parsing 21 | { 22 | /// 23 | /// Parses message template strings into sequences of text or property 24 | /// tokens. 25 | /// 26 | public class MessageTemplateParser : IMessageTemplateParser 27 | { 28 | /// 29 | /// Parse the supplied message template. 30 | /// 31 | /// The message template to parse. 32 | /// A sequence of text or property tokens. Where the template 33 | /// is not syntactically valid, text tokens will be returned. The parser 34 | /// will make a best effort to extract valid property tokens even in the 35 | /// presence of parsing issues. 36 | public MessageTemplate Parse(string messageTemplate) 37 | { 38 | if (messageTemplate == null) 39 | throw new ArgumentNullException(nameof(messageTemplate)); 40 | return new MessageTemplate(messageTemplate, Tokenize(messageTemplate)); 41 | } 42 | 43 | static IEnumerable Tokenize(string messageTemplate) 44 | { 45 | if (messageTemplate == "") 46 | { 47 | yield return new TextToken("", 0); 48 | yield break; 49 | } 50 | 51 | var nextIndex = 0; 52 | while (true) 53 | { 54 | var beforeText = nextIndex; 55 | var tt = ParseTextToken(nextIndex, messageTemplate, out nextIndex); 56 | if (nextIndex > beforeText) 57 | yield return tt; 58 | 59 | if (nextIndex == messageTemplate.Length) 60 | yield break; 61 | 62 | var beforeProp = nextIndex; 63 | var pt = ParsePropertyToken(nextIndex, messageTemplate, out nextIndex); 64 | if (beforeProp < nextIndex) 65 | yield return pt; 66 | 67 | if (nextIndex == messageTemplate.Length) 68 | yield break; 69 | } 70 | } 71 | 72 | static MessageTemplateToken ParsePropertyToken(int startAt, string messageTemplate, out int next) 73 | { 74 | var first = startAt; 75 | startAt++; 76 | while (startAt < messageTemplate.Length && IsValidInPropertyTag(messageTemplate[startAt])) 77 | startAt++; 78 | 79 | if (startAt == messageTemplate.Length || messageTemplate[startAt] != '}') 80 | { 81 | next = startAt; 82 | return new TextToken(messageTemplate.Substring(first, next - first), first); 83 | } 84 | 85 | next = startAt + 1; 86 | 87 | var rawText = messageTemplate.Substring(first, next - first); 88 | var tagContent = messageTemplate.Substring(first + 1, next - (first + 2)); 89 | if (tagContent.Length == 0 || 90 | !IsValidInPropertyTag(tagContent[0])) 91 | return new TextToken(rawText, first); 92 | 93 | if (!TrySplitTagContent(tagContent, out var propertyNameAndDestructuring, out var format, out var alignment)) 94 | return new TextToken(rawText, first); 95 | 96 | var propertyName = propertyNameAndDestructuring; 97 | if (TryGetDestructuringHint(propertyName[0], out var destructuring)) 98 | propertyName = propertyName.Substring(1); 99 | 100 | if (propertyName == "" || !IsValidInPropertyName(propertyName[0])) 101 | return new TextToken(rawText, first); 102 | 103 | for (var i = 0; i < propertyName.Length; ++i) 104 | { 105 | var c = propertyName[i]; 106 | if (!IsValidInPropertyName(c)) 107 | return new TextToken(rawText, first); 108 | } 109 | 110 | if (format != null) 111 | { 112 | for (var i = 0; i < format.Length; ++i) 113 | { 114 | var c = format[i]; 115 | if (!IsValidInFormat(c)) 116 | return new TextToken(rawText, first); 117 | } 118 | } 119 | 120 | Alignment? alignmentValue = null; 121 | if (alignment != null) 122 | { 123 | for (var i = 0; i < alignment.Length; ++i) 124 | { 125 | var c = alignment[i]; 126 | if (!IsValidInAlignment(c)) 127 | return new TextToken(rawText, first); 128 | } 129 | 130 | var lastDash = alignment.LastIndexOf('-'); 131 | if (lastDash > 0) 132 | return new TextToken(rawText, first); 133 | 134 | var width = lastDash == -1 ? 135 | int.Parse(alignment) : 136 | int.Parse(alignment.Substring(1)); 137 | 138 | if (width == 0) 139 | return new TextToken(rawText, first); 140 | 141 | var direction = lastDash == -1 ? 142 | AlignmentDirection.Right : 143 | AlignmentDirection.Left; 144 | 145 | alignmentValue = new Alignment(direction, width); 146 | } 147 | 148 | return new PropertyToken( 149 | propertyName, 150 | rawText, 151 | format, 152 | alignmentValue, 153 | destructuring, 154 | first); 155 | } 156 | 157 | static bool TrySplitTagContent(string tagContent, out string propertyNameAndDestructuring, out string format, out string alignment) 158 | { 159 | var formatDelim = tagContent.IndexOf(':'); 160 | var alignmentDelim = tagContent.IndexOf(','); 161 | if (formatDelim == -1 && alignmentDelim == -1) 162 | { 163 | propertyNameAndDestructuring = tagContent; 164 | format = null; 165 | alignment = null; 166 | } 167 | else 168 | { 169 | if (alignmentDelim == -1 || (formatDelim != -1 && alignmentDelim > formatDelim)) 170 | { 171 | propertyNameAndDestructuring = tagContent.Substring(0, formatDelim); 172 | format = formatDelim == tagContent.Length - 1 ? 173 | null : 174 | tagContent.Substring(formatDelim + 1); 175 | alignment = null; 176 | } 177 | else 178 | { 179 | propertyNameAndDestructuring = tagContent.Substring(0, alignmentDelim); 180 | if (formatDelim == -1) 181 | { 182 | if (alignmentDelim == tagContent.Length - 1) 183 | { 184 | alignment = format = null; 185 | return false; 186 | } 187 | 188 | format = null; 189 | alignment = tagContent.Substring(alignmentDelim + 1); 190 | } 191 | else 192 | { 193 | if (alignmentDelim == formatDelim - 1) 194 | { 195 | alignment = format = null; 196 | return false; 197 | } 198 | 199 | alignment = tagContent.Substring(alignmentDelim + 1, formatDelim - alignmentDelim - 1); 200 | format = formatDelim == tagContent.Length - 1 ? 201 | null : 202 | tagContent.Substring(formatDelim + 1); 203 | } 204 | } 205 | } 206 | 207 | return true; 208 | } 209 | 210 | static bool IsValidInPropertyTag(char c) 211 | { 212 | return IsValidInDestructuringHint(c) || 213 | IsValidInPropertyName(c) || 214 | IsValidInFormat(c) || 215 | c == ':'; 216 | } 217 | 218 | static bool IsValidInPropertyName(char c) 219 | { 220 | return char.IsLetterOrDigit(c) || c == '_'; 221 | } 222 | 223 | static bool TryGetDestructuringHint(char c, out Destructuring destructuring) 224 | { 225 | switch (c) 226 | { 227 | case '@': 228 | { 229 | destructuring = Destructuring.Destructure; 230 | return true; 231 | } 232 | case '$': 233 | { 234 | destructuring = Destructuring.Stringify; 235 | return true; 236 | } 237 | default: 238 | { 239 | destructuring = Destructuring.Default; 240 | return false; 241 | } 242 | } 243 | } 244 | 245 | static bool IsValidInDestructuringHint(char c) 246 | { 247 | return c == '@' || 248 | c == '$'; 249 | } 250 | 251 | static bool IsValidInAlignment(char c) 252 | { 253 | return char.IsDigit(c) || 254 | c == '-'; 255 | } 256 | 257 | static bool IsValidInFormat(char c) 258 | { 259 | return c != '}' && 260 | (char.IsLetterOrDigit(c) || 261 | char.IsPunctuation(c) || 262 | c == ' '); 263 | } 264 | 265 | static TextToken ParseTextToken(int startAt, string messageTemplate, out int next) 266 | { 267 | var first = startAt; 268 | 269 | var accum = new StringBuilder(); 270 | do 271 | { 272 | var nc = messageTemplate[startAt]; 273 | if (nc == '{') 274 | { 275 | if (startAt + 1 < messageTemplate.Length && 276 | messageTemplate[startAt + 1] == '{') 277 | { 278 | accum.Append(nc); 279 | startAt++; 280 | } 281 | else 282 | { 283 | break; 284 | } 285 | } 286 | else 287 | { 288 | accum.Append(nc); 289 | if (nc == '}') 290 | { 291 | if (startAt + 1 < messageTemplate.Length && 292 | messageTemplate[startAt + 1] == '}') 293 | { 294 | startAt++; 295 | } 296 | } 297 | } 298 | 299 | startAt++; 300 | } while (startAt < messageTemplate.Length); 301 | 302 | next = startAt; 303 | return new TextToken(accum.ToString(), first); 304 | } 305 | } 306 | } 307 | -------------------------------------------------------------------------------- /src/MessageTemplates/Parameters/PropertyValueConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2015 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 System; 16 | using System.Collections; 17 | using System.Collections.Generic; 18 | using System.Linq; 19 | using System.Reflection; 20 | using System.Runtime.CompilerServices; 21 | using MessageTemplates.Core; 22 | using MessageTemplates.Debugging; 23 | using MessageTemplates.Structure; 24 | using MessageTemplates.Parsing; 25 | using MessageTemplates.Policies; 26 | 27 | namespace MessageTemplates.Parameters 28 | { 29 | // Values in MessageTemplates are simplified down into a lowest-common-denominator internal 30 | // type system so that there is a better chance of code written with one sink in 31 | // mind working correctly with any other. This technique also makes the programmer 32 | // writing a log event (roughly) in control of the cost of recording that event. 33 | partial class PropertyValueConverter : IMessageTemplatePropertyValueFactory 34 | { 35 | static readonly HashSet BuiltInScalarTypes = new HashSet 36 | { 37 | typeof(bool), 38 | typeof(char), 39 | typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), 40 | typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(decimal), 41 | typeof(string), 42 | typeof(DateTime), typeof(DateTimeOffset), typeof(TimeSpan), 43 | typeof(Guid), typeof(Uri) 44 | }; 45 | 46 | readonly IDestructuringPolicy[] _destructuringPolicies; 47 | readonly IScalarConversionPolicy[] _scalarConversionPolicies; 48 | readonly int _maximumDestructuringDepth; 49 | 50 | public PropertyValueConverter(int maximumDestructuringDepth, IEnumerable additionalScalarTypes, IEnumerable additionalDestructuringPolicies) 51 | { 52 | if (additionalScalarTypes == null) throw new ArgumentNullException(nameof(additionalScalarTypes)); 53 | if (additionalDestructuringPolicies == null) throw new ArgumentNullException(nameof(additionalDestructuringPolicies)); 54 | if (maximumDestructuringDepth < 0) throw new ArgumentOutOfRangeException(nameof(maximumDestructuringDepth)); 55 | 56 | _maximumDestructuringDepth = maximumDestructuringDepth; 57 | 58 | _scalarConversionPolicies = new IScalarConversionPolicy[] 59 | { 60 | new SimpleScalarConversionPolicy(BuiltInScalarTypes.Concat(additionalScalarTypes)), 61 | new NullableScalarConversionPolicy(), 62 | new EnumScalarConversionPolicy(), 63 | new ByteArrayScalarConversionPolicy(), 64 | }; 65 | 66 | _destructuringPolicies = additionalDestructuringPolicies 67 | .Concat(new IDestructuringPolicy [] 68 | { 69 | new DelegateDestructuringPolicy(), 70 | new ReflectionTypesScalarDestructuringPolicy() 71 | }) 72 | .ToArray(); 73 | } 74 | 75 | public TemplateProperty CreateProperty(string name, object value, bool destructureObjects = false) 76 | { 77 | return new TemplateProperty(name, CreatePropertyValue(value, destructureObjects)); 78 | } 79 | 80 | public TemplatePropertyValue CreatePropertyValue(object value, bool destructureObjects = false) 81 | { 82 | return CreatePropertyValue(value, destructureObjects, 1); 83 | } 84 | 85 | public TemplatePropertyValue CreatePropertyValue(object value, Destructuring destructuring) 86 | { 87 | return CreatePropertyValue(value, destructuring, 1); 88 | } 89 | 90 | TemplatePropertyValue CreatePropertyValue(object value, bool destructureObjects, int depth) 91 | { 92 | return CreatePropertyValue( 93 | value, 94 | destructureObjects ? 95 | Destructuring.Destructure : 96 | Destructuring.Default, 97 | depth); 98 | } 99 | 100 | TemplatePropertyValue CreatePropertyValue(object value, Destructuring destructuring, int depth) 101 | { 102 | if (value == null) 103 | return new ScalarValue(null); 104 | 105 | if (destructuring == Destructuring.Stringify) 106 | return new ScalarValue(value.ToString()); 107 | 108 | var valueType = value.GetType(); 109 | var limiter = new DepthLimiter(depth, _maximumDestructuringDepth, this); 110 | 111 | foreach (var scalarConversionPolicy in _scalarConversionPolicies) 112 | { 113 | if (scalarConversionPolicy.TryConvertToScalar(value, limiter, out var converted)) 114 | return converted; 115 | } 116 | 117 | if (destructuring == Destructuring.Destructure) 118 | { 119 | foreach (var destructuringPolicy in _destructuringPolicies) 120 | { 121 | if (destructuringPolicy.TryDestructure(value, limiter, out var result)) 122 | return result; 123 | } 124 | } 125 | 126 | if (value is IEnumerable enumerable) 127 | { 128 | // Only dictionaries with 'scalar' keys are permitted, as 129 | // more complex keys may not serialize to unique values for 130 | // representation in sinks. This check strengthens the expectation 131 | // that resulting dictionary is representable in JSON as well 132 | // as richer formats (e.g. XML, .NET type-aware...). 133 | // Only actual dictionaries are supported, as arbitrary types 134 | // can implement multiple IDictionary interfaces and thus introduce 135 | // multiple different interpretations. 136 | if (IsValueTypeDictionary(valueType)) 137 | { 138 | Func getKey; 139 | Func getValue; 140 | #if !REFLECTION_API_EVOLVED // https://blogs.msdn.microsoft.com/dotnet/2012/08/28/evolving-the-reflection-api/ 141 | PropertyInfo keyProperty = null; 142 | getKey = o => (keyProperty ?? (keyProperty = o.GetType().GetProperty("Key"))).GetValue(o, null); 143 | PropertyInfo valueProperty = null; 144 | getValue = o => (valueProperty ?? (valueProperty = o.GetType().GetProperty("Value"))).GetValue(o, null); 145 | #else 146 | PropertyInfo keyProperty = null; 147 | getKey = o => (keyProperty ?? (keyProperty = o.GetType().GetRuntimeProperty("Key"))).GetValue(o); 148 | PropertyInfo valueProperty = null; 149 | getValue = o => (valueProperty ?? (valueProperty = o.GetType().GetRuntimeProperty("Value"))).GetValue(o); 150 | #endif 151 | 152 | // TODO: stop using LINQ 153 | return new DictionaryValue(enumerable 154 | .Cast() 155 | .Where(o => o != null) 156 | .Select(o => new { Key = getKey(o), Value = getValue(o) }) 157 | .Select(o => new KeyValuePair( 158 | key: (ScalarValue)limiter.CreatePropertyValue(o.Key, destructuring), 159 | value: limiter.CreatePropertyValue(o.Value, destructuring)) 160 | ) 161 | ); 162 | } 163 | 164 | return new SequenceValue( 165 | enumerable.Cast().Select(o => limiter.CreatePropertyValue(o, destructuring))); 166 | } 167 | 168 | if (destructuring == Destructuring.Destructure) 169 | { 170 | var type = value.GetType(); 171 | var typeTag = type.Name; 172 | #if REFLECTION_API_EVOLVED 173 | if (typeTag.Length <= 0 || IsCompilerGeneratedType(type)) 174 | typeTag = null; 175 | #else 176 | if (typeTag.Length <= 0 || !char.IsLetter(typeTag[0])) 177 | typeTag = null; 178 | #endif 179 | return new StructureValue(GetProperties(value, limiter), typeTag); 180 | } 181 | 182 | return new ScalarValue(value.ToString()); 183 | } 184 | 185 | static bool IsValueTypeDictionary(Type valueType) 186 | { 187 | #if !REFLECTION_API_EVOLVED // https://blogs.msdn.microsoft.com/dotnet/2012/08/28/evolving-the-reflection-api/ 188 | return valueType.IsGenericType && 189 | valueType.GetGenericTypeDefinition() == typeof(Dictionary<,>) && 190 | IsValidDictionaryKeyType(valueType.GetGenericArguments()[0]); 191 | #else 192 | return valueType.IsConstructedGenericType && 193 | valueType.GetGenericTypeDefinition() == typeof(Dictionary<,>) && 194 | IsValidDictionaryKeyType(valueType.GenericTypeArguments[0]); 195 | #endif 196 | } 197 | 198 | static bool IsValidDictionaryKeyType(Type valueType) 199 | { 200 | return BuiltInScalarTypes.Contains(valueType) || 201 | #if !REFLECTION_API_EVOLVED // https://blogs.msdn.microsoft.com/dotnet/2012/08/28/evolving-the-reflection-api/ 202 | valueType.IsEnum; 203 | #else 204 | valueType.GetTypeInfo().IsEnum; 205 | #endif 206 | } 207 | 208 | static IEnumerable GetProperties( 209 | object value, IMessageTemplatePropertyValueFactory recursive) 210 | { 211 | var properties = 212 | 213 | #if !REFLECTION_API_EVOLVED 214 | // TODO: stop using LINQ 215 | value.GetType().GetProperties().Where(p => p.CanRead && 216 | p.GetGetMethod().IsPublic && 217 | !p.GetGetMethod().IsStatic && 218 | (p.Name != "Item" || p.GetIndexParameters().Length == 0)); 219 | #else 220 | value.GetType().GetPropertiesRecursive(); 221 | #endif 222 | foreach (var prop in properties) 223 | { 224 | object propValue; 225 | try 226 | { 227 | #if !REFLECTION_API_EVOLVED // https://blogs.msdn.microsoft.com/dotnet/2012/08/28/evolving-the-reflection-api/ 228 | propValue = prop.GetValue(value, null); 229 | #else 230 | propValue = prop.GetValue(value); 231 | #endif 232 | } 233 | catch (TargetParameterCountException) 234 | { 235 | SelfLog.WriteLine("The property accessor {0} is a non-default indexer", prop); 236 | continue; 237 | } 238 | catch (TargetInvocationException ex) 239 | { 240 | SelfLog.WriteLine("The property accessor {0} threw exception {1}", prop, ex); 241 | propValue = "The property accessor threw an exception: " + ex.InnerException.GetType().Name; 242 | } 243 | yield return new TemplateProperty(prop.Name, recursive.CreatePropertyValue(propValue, true)); 244 | } 245 | } 246 | 247 | #if REFLECTION_API_EVOLVED // https://blogs.msdn.microsoft.com/dotnet/2012/08/28/evolving-the-reflection-api/ 248 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 249 | // ReSharper disable once MemberCanBePrivate.Global 250 | internal static bool IsCompilerGeneratedType(Type type) 251 | { 252 | var typeInfo = type.GetTypeInfo(); 253 | var typeName = type.Name; 254 | 255 | //C# Anonymous types always start with "<>" and VB's start with "VB$" 256 | return typeInfo.IsGenericType && typeInfo.IsSealed && typeInfo.IsNotPublic && type.Namespace == null 257 | && (typeName[0] == '<' 258 | || (typeName.Length > 2 && typeName[0] == 'V' && typeName[1] == 'B' && typeName[2] == '$')); 259 | } 260 | #endif 261 | } 262 | } 263 | -------------------------------------------------------------------------------- /src/MessageTemplates/Formatting/JsonValueFormatter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 MessageTemplates 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 System; 16 | using System.Globalization; 17 | using System.IO; 18 | using MessageTemplates.Data; 19 | using MessageTemplates.Structure; 20 | 21 | namespace MessageTemplates.Formatting 22 | { 23 | /// 24 | /// Converts MessageTemplates's structured property value format into JSON. 25 | /// 26 | public class JsonValueFormatter : TemplatePropertyValueVisitor 27 | { 28 | readonly string _typeTagName; 29 | 30 | const string DefaultTypeTagName = "_typeTag"; 31 | 32 | /// 33 | /// Construct a . 34 | /// 35 | /// When serializing structured (object) values, 36 | /// the property name to use for the MessageTemplates field 37 | /// in the resulting JSON. If null, no type tag field will be written. The default is 38 | /// "_typeTag". 39 | public JsonValueFormatter(string typeTagName = DefaultTypeTagName) 40 | { 41 | _typeTagName = typeTagName; 42 | } 43 | 44 | /// 45 | /// Format as JSON to . 46 | /// 47 | /// The value to format 48 | /// The output 49 | public void Format(TemplatePropertyValue value, TextWriter output) 50 | { 51 | // Parameter order of ITextFormatter is the reverse of the visitor one. 52 | // In this class, public methods and methods with Format*() names use the 53 | // (x, output) parameter naming convention. 54 | Visit(output, value); 55 | } 56 | 57 | /// 58 | /// Visit a value. 59 | /// 60 | /// Operation state. 61 | /// The value to visit. 62 | /// The result of visiting . 63 | protected override bool VisitScalarValue(TextWriter state, ScalarValue scalar) 64 | { 65 | if (scalar == null) throw new ArgumentNullException(nameof(scalar)); 66 | FormatLiteralValue(scalar.Value, state); 67 | return false; 68 | } 69 | 70 | /// 71 | /// Visit a value. 72 | /// 73 | /// Operation state. 74 | /// The value to visit. 75 | /// The result of visiting . 76 | protected override bool VisitSequenceValue(TextWriter state, SequenceValue sequence) 77 | { 78 | if (sequence == null) throw new ArgumentNullException(nameof(sequence)); 79 | state.Write('['); 80 | var delim = ""; 81 | for (var i = 0; i < sequence.Elements.Count; i++) 82 | { 83 | state.Write(delim); 84 | delim = ","; 85 | Visit(state, sequence.Elements[i]); 86 | } 87 | state.Write(']'); 88 | return false; 89 | } 90 | 91 | /// 92 | /// Visit a value. 93 | /// 94 | /// Operation state. 95 | /// The value to visit. 96 | /// The result of visiting . 97 | protected override bool VisitStructureValue(TextWriter state, StructureValue structure) 98 | { 99 | state.Write('{'); 100 | 101 | var delim = ""; 102 | 103 | for (var i = 0; i < structure.Properties.Count; i++) 104 | { 105 | state.Write(delim); 106 | delim = ","; 107 | var prop = structure.Properties[i]; 108 | WriteQuotedJsonString(prop.Name, state); 109 | state.Write(':'); 110 | Visit(state, prop.Value); 111 | } 112 | 113 | if (_typeTagName != null && structure.TypeTag != null) 114 | { 115 | state.Write(delim); 116 | WriteQuotedJsonString(_typeTagName, state); 117 | state.Write(':'); 118 | WriteQuotedJsonString(structure.TypeTag, state); 119 | } 120 | 121 | state.Write('}'); 122 | return false; 123 | } 124 | 125 | /// 126 | /// Visit a value. 127 | /// 128 | /// Operation state. 129 | /// The value to visit. 130 | /// The result of visiting . 131 | protected override bool VisitDictionaryValue(TextWriter state, DictionaryValue dictionary) 132 | { 133 | state.Write('{'); 134 | var delim = ""; 135 | foreach (var element in dictionary.Elements) 136 | { 137 | state.Write(delim); 138 | delim = ","; 139 | WriteQuotedJsonString((element.Key.Value ?? "null").ToString(), state); 140 | state.Write(':'); 141 | Visit(state, element.Value); 142 | } 143 | state.Write('}'); 144 | return false; 145 | } 146 | 147 | /// 148 | /// Write a literal as a single JSON value, e.g. as a number or string. Override to 149 | /// support more value types. Don't write arrays/structures through this method - the 150 | /// active destructuring policies have already indicated the value should be scalar at 151 | /// this point. 152 | /// 153 | /// The value to write. 154 | /// The output 155 | protected virtual void FormatLiteralValue(object value, TextWriter output) 156 | { 157 | if (value == null) 158 | { 159 | FormatNullValue(output); 160 | return; 161 | } 162 | 163 | // Although the linear switch-on-type has apparently worse algorithmic performance than the O(1) 164 | // dictionary lookup alternative, in practice, it's much to make a few equality comparisons 165 | // than the hash/bucket dictionary lookup, and since most data will be string (one comparison), 166 | // numeric (a handful) or an object (two comparsions) the real-world performance of the code 167 | // as written is as fast or faster. 168 | 169 | if (value is string str) 170 | { 171 | FormatStringValue(str, output); 172 | return; 173 | } 174 | 175 | if (value is ValueType) 176 | { 177 | if (value is int || value is uint || value is long || value is ulong || value is decimal || 178 | value is byte || value is sbyte || value is short || value is ushort) 179 | { 180 | FormatExactNumericValue((IFormattable)value, output); 181 | return; 182 | } 183 | 184 | if (value is double || value is float) 185 | { 186 | FormatApproximateNumericValue((IFormattable)value, output); 187 | return; 188 | } 189 | 190 | if (value is bool b) 191 | { 192 | FormatBooleanValue(b, output); 193 | return; 194 | } 195 | 196 | if (value is char) 197 | { 198 | FormatStringValue(value.ToString(), output); 199 | return; 200 | } 201 | 202 | if (value is DateTime || value is DateTimeOffset) 203 | { 204 | FormatDateTimeValue((IFormattable)value, output); 205 | return; 206 | } 207 | 208 | if (value is TimeSpan span) 209 | { 210 | FormatTimeSpanValue(span, output); 211 | return; 212 | } 213 | } 214 | 215 | FormatLiteralObjectValue(value, output); 216 | } 217 | 218 | static void FormatBooleanValue(bool value, TextWriter output) 219 | { 220 | output.Write(value ? "true" : "false"); 221 | } 222 | 223 | static void FormatApproximateNumericValue(IFormattable value, TextWriter output) 224 | { 225 | output.Write(value.ToString("R", CultureInfo.InvariantCulture)); 226 | } 227 | 228 | static void FormatExactNumericValue(IFormattable value, TextWriter output) 229 | { 230 | output.Write(value.ToString(null, CultureInfo.InvariantCulture)); 231 | } 232 | 233 | static void FormatDateTimeValue(IFormattable value, TextWriter output) 234 | { 235 | output.Write('\"'); 236 | output.Write(value.ToString("O", CultureInfo.InvariantCulture)); 237 | output.Write('\"'); 238 | } 239 | 240 | static void FormatTimeSpanValue(TimeSpan value, TextWriter output) 241 | { 242 | output.Write('\"'); 243 | output.Write(value.ToString()); 244 | output.Write('\"'); 245 | } 246 | 247 | static void FormatLiteralObjectValue(object value, TextWriter output) 248 | { 249 | if (value == null) throw new ArgumentNullException(nameof(value)); 250 | FormatStringValue(value.ToString(), output); 251 | } 252 | 253 | static void FormatStringValue(string str, TextWriter output) 254 | { 255 | WriteQuotedJsonString(str, output); 256 | } 257 | 258 | static void FormatNullValue(TextWriter output) 259 | { 260 | output.Write("null"); 261 | } 262 | 263 | /// 264 | /// Write a valid JSON string literal, escaping as necessary. 265 | /// 266 | /// The string value to write. 267 | /// The output. 268 | public static void WriteQuotedJsonString(string str, TextWriter output) 269 | { 270 | output.Write('\"'); 271 | 272 | var cleanSegmentStart = 0; 273 | var anyEscaped = false; 274 | 275 | for (var i = 0; i < str.Length; ++i) 276 | { 277 | var c = str[i]; 278 | if (c < (char)32 || c == '\\' || c == '"') 279 | { 280 | anyEscaped = true; 281 | 282 | output.Write(str.Substring(cleanSegmentStart, i - cleanSegmentStart)); 283 | cleanSegmentStart = i + 1; 284 | 285 | switch (c) 286 | { 287 | case '"': 288 | { 289 | output.Write("\\\""); 290 | break; 291 | } 292 | case '\\': 293 | { 294 | output.Write("\\\\"); 295 | break; 296 | } 297 | case '\n': 298 | { 299 | output.Write("\\n"); 300 | break; 301 | } 302 | case '\r': 303 | { 304 | output.Write("\\r"); 305 | break; 306 | } 307 | case '\f': 308 | { 309 | output.Write("\\f"); 310 | break; 311 | } 312 | case '\t': 313 | { 314 | output.Write("\\t"); 315 | break; 316 | } 317 | default: 318 | { 319 | output.Write("\\u"); 320 | output.Write(((int)c).ToString("X4")); 321 | break; 322 | } 323 | } 324 | } 325 | } 326 | 327 | if (anyEscaped) 328 | { 329 | if (cleanSegmentStart != str.Length) 330 | output.Write(str.Substring(cleanSegmentStart)); 331 | } 332 | else 333 | { 334 | output.Write(str); 335 | } 336 | 337 | output.Write('\"'); 338 | } 339 | } 340 | } --------------------------------------------------------------------------------