Provides registration information for named items (targets, layouts, layout renderers, etc.) managed by NLog.
 public void LayoutRendererThrows()
 {
     ConfigurationItemFactory configurationItemFactory = new ConfigurationItemFactory();
     configurationItemFactory.LayoutRenderers.RegisterDefinition("throwsException", typeof(ThrowsExceptionRenderer));
     
     SimpleLayout l = new SimpleLayout("xx${throwsException}yy", configurationItemFactory);
     string output = l.Render(LogEventInfo.CreateNullEvent());
     Assert.AreEqual("xxyy", output);
 }
Beispiel #2
0
        internal static LayoutRenderer[] CompileLayout(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr, bool isNested, out string text)
        {
            var result = new List<LayoutRenderer>();
            var literalBuf = new StringBuilder();

            int ch;

            int p0 = sr.Position;

            while ((ch = sr.Peek()) != -1)
            {
                if (isNested && (ch == '}' || ch == ':'))
                {
                    break;
                }

                sr.Read();

                if (ch == '$' && sr.Peek() == '{')
                {
                    if (literalBuf.Length > 0)
                    {
                        result.Add(new LiteralLayoutRenderer(literalBuf.ToString()));
                        literalBuf.Length = 0;
                    }

                    LayoutRenderer newLayoutRenderer = ParseLayoutRenderer(configurationItemFactory, sr);
                    if (CanBeConvertedToLiteral(newLayoutRenderer))
                    {
                        newLayoutRenderer = ConvertToLiteral(newLayoutRenderer);
                    }

                    // layout renderer
                    result.Add(newLayoutRenderer);
                }
                else
                {
                    literalBuf.Append((char)ch);
                }
            }

            if (literalBuf.Length > 0)
            {
                result.Add(new LiteralLayoutRenderer(literalBuf.ToString()));
                literalBuf.Length = 0;
            }

            int p1 = sr.Position;

            MergeLiterals(result);
            text = sr.Substring(p0, p1);

            return result.ToArray();
        }
Beispiel #3
0
        internal static void SetPropertyFromString(object o, string name, string value, ConfigurationItemFactory configurationItemFactory)
        {
            InternalLogger.Debug("Setting '{0}.{1}' to '{2}'", o.GetType().Name, name, value);

            PropertyInfo propInfo;

            if (!TryGetPropertyInfo(o, name, out propInfo))
            {
                throw new NotSupportedException("Parameter " + name + " not supported on " + o.GetType().Name);
            }

            try
            {
                if (propInfo.IsDefined(typeof(ArrayParameterAttribute), false))
                {
                    throw new NotSupportedException("Parameter " + name + " of " + o.GetType().Name + " is an array and cannot be assigned a scalar value.");
                }

                object newValue;

                Type propertyType = propInfo.PropertyType;

                propertyType = Nullable.GetUnderlyingType(propertyType) ?? propertyType;

                if (!TryNLogSpecificConversion(propertyType, value, out newValue, configurationItemFactory))
                {
                    if (!TryGetEnumValue(propertyType, value, out newValue))
                    {
                        if (!TryImplicitConversion(propertyType, value, out newValue))
                        {
                            if (!TrySpecialConversion(propertyType, value, out newValue))
                            {
                                newValue = Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture);
                            }
                        }
                    }
                }

                propInfo.SetValue(o, newValue, null);
            }
            catch (TargetInvocationException ex)
            {
                throw new NLogConfigurationException("Error when setting property '" + propInfo.Name + "' on " + o, ex.InnerException);
            }
            catch (Exception exception)
            {
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                throw new NLogConfigurationException("Error when setting property '" + propInfo.Name + "' on " + o, exception);
            }
        }
        /// <summary>
        /// Registers the Rebus correlation ID renderer under the <see cref="ItemName"/> key in the given <see cref="ConfigurationItemFactory"/>
        /// </summary>
        public static void Register(ConfigurationItemFactory configurationItemFactory)
        {
            var namedItemFactory = configurationItemFactory.LayoutRenderers;

            Type dummy;
            var layoutRendererHasAlreadyBeenBeenRegistered = namedItemFactory
                .TryGetDefinition(ItemName, out dummy);

            if (layoutRendererHasAlreadyBeenBeenRegistered)
            {
                return;
            }

            namedItemFactory.RegisterDefinition(ItemName, typeof (RebusCorrelationIdLayoutRenderer));
        }
Beispiel #5
0
        /// <summary>
        /// Parses the specified condition string and turns it into
        /// <see cref="ConditionExpression"/> tree.
        /// </summary>
        /// <param name="expressionText">The expression to be parsed.</param>
        /// <param name="configurationItemFactories">Instance of <see cref="ConfigurationItemFactory"/> used to resolve references to condition methods and layout renderers.</param>
        /// <returns>The root of the expression syntax tree which can be used to get the value of the condition in a specified context.</returns>
        public static ConditionExpression ParseExpression(string expressionText, ConfigurationItemFactory configurationItemFactories)
        {
            if (expressionText == null)
            {
                return null;
            }

            var parser = new ConditionParser(new SimpleStringReader(expressionText), configurationItemFactories);
            ConditionExpression expression = parser.ParseExpression();
            if (!parser.tokenizer.IsEOF())
            {
                throw new ConditionParseException("Unexpected token: " + parser.tokenizer.TokenValue);
            }

            return expression;
        }
Beispiel #6
0
        /// <summary>
        /// Builds the default configuration item factory.
        /// </summary>
        /// <returns>Default factory.</returns>
        private static ConfigurationItemFactory BuildDefaultFactory()
        {
            var nlogAssembly = typeof(ILogger).Assembly;
            var factory      = new ConfigurationItemFactory(nlogAssembly);

            factory.RegisterExtendedItems();
#if !SILVERLIGHT
            var assemblyLocation = Path.GetDirectoryName(new Uri(nlogAssembly.CodeBase).LocalPath);
            if (assemblyLocation == null)
            {
                InternalLogger.Warn("No auto loading because Nlog.dll location is unknown");
                return(factory);
            }

            var extensionDlls = Directory.GetFiles(assemblyLocation, "NLog*.dll")
                                .Select(Path.GetFileName)
                                .Where(x => !x.Equals("NLog.dll", StringComparison.OrdinalIgnoreCase))
                                .Where(x => !x.Equals("NLog.UnitTests.dll", StringComparison.OrdinalIgnoreCase))
                                .Where(x => !x.Equals("NLog.Extended.dll", StringComparison.OrdinalIgnoreCase))
                                .Select(x => Path.Combine(assemblyLocation, x));

            InternalLogger.Debug("Start auto loading, location: {0}", assemblyLocation);
            foreach (var extensionDll in extensionDlls)
            {
                InternalLogger.Info("Auto loading assembly file: {0}", extensionDll);
                var success = false;
                try
                {
                    var extensionAssembly = Assembly.LoadFrom(extensionDll);
                    factory.RegisterItemsFromAssembly(extensionAssembly);
                    success = true;
                }
                catch (Exception)
                {
                    InternalLogger.Warn("Auto loading assembly file: {0} failed! Skipping this file.", extensionDll);
                }
                if (success)
                {
                    InternalLogger.Info("Auto loading assembly file: {0} succeeded!", extensionDll);
                }
            }
            InternalLogger.Debug("Auto loading done");
#endif

            return(factory);
        }
Beispiel #7
0
        public void LayoutRendererThrows2()
        {
            string internalLogOutput = RunAndCaptureInternalLog(
                () =>
                    {
                        ConfigurationItemFactory configurationItemFactory = new ConfigurationItemFactory();
                        configurationItemFactory.LayoutRenderers.RegisterDefinition("throwsException", typeof(ThrowsExceptionRenderer));

                        SimpleLayout l = new SimpleLayout("xx${throwsException:msg1}yy${throwsException:msg2}zz", new LoggingConfiguration(configurationItemFactory));
                        l.Initialize(CommonCfg);
                        string output = l.Render(LogEventInfo.CreateNullEvent());
                        Assert.AreEqual("xxyyzz", output);
                    },
                    LogLevel.Warn);

            Assert.IsTrue(internalLogOutput.IndexOf("msg1") >= 0, internalLogOutput);
            Assert.IsTrue(internalLogOutput.IndexOf("msg2") >= 0, internalLogOutput);
        }
 /// <summary>
 /// Initializes static members of the <see cref="ConfigurationItemFactory"/> class.
 /// </summary>
 static ConfigurationItemFactory()
 {
     Default = new ConfigurationItemFactory(typeof(Logger).Assembly);
 }
        /// <summary>
        /// Builds the default configuration item factory.
        /// </summary>
        /// <returns>Default factory.</returns>
        private static ConfigurationItemFactory BuildDefaultFactory()
        {
            var nlogAssembly = typeof(ILogger).Assembly;
            var factory = new ConfigurationItemFactory(nlogAssembly);
            factory.RegisterExtendedItems();
#if !SILVERLIGHT
            var assemblyLocation = Path.GetDirectoryName(nlogAssembly.Location);
            if (assemblyLocation == null)
            {
                return factory;
            }

            var extensionDlls = Directory.GetFiles(assemblyLocation, "NLog*.dll")
                .Select(Path.GetFileName)
                .Where(x => !x.Equals("NLog.dll", StringComparison.OrdinalIgnoreCase))
                .Where(x => !x.Equals("NLog.UnitTests.dll", StringComparison.OrdinalIgnoreCase))
                .Where(x => !x.Equals("NLog.Extended.dll", StringComparison.OrdinalIgnoreCase))
                .Select(x => Path.Combine(assemblyLocation, x));
            foreach (var extensionDll in extensionDlls)
            {
                InternalLogger.Info("Auto loading assembly file: {0}", extensionDll);
                var extensionAssembly = Assembly.LoadFrom(extensionDll);
                factory.RegisterItemsFromAssembly(extensionAssembly);
            }
#endif

            return factory;
        }
        /// <summary>
        /// Builds the default configuration item factory.
        /// </summary>
        /// <returns>Default factory.</returns>
        private static ConfigurationItemFactory BuildDefaultFactory()
        {
            var nlogAssembly = typeof(ILogger).Assembly;
            var factory = new ConfigurationItemFactory(nlogAssembly);
            factory.RegisterExtendedItems();
#if !SILVERLIGHT

            var assemblyLocation = Path.GetDirectoryName(new Uri(nlogAssembly.CodeBase).LocalPath);
            if (assemblyLocation == null)
            {
                InternalLogger.Warn("No auto loading because Nlog.dll location is unknown");
                return factory;
            }
            if (!Directory.Exists(assemblyLocation))
            {
                InternalLogger.Warn("No auto loading because '{0}' doesn't exists", assemblyLocation);
                return factory;
            }

            try
            {

                var extensionDlls = Directory.GetFiles(assemblyLocation, "NLog*.dll")
                    .Select(Path.GetFileName)
                    .Where(x => !x.Equals("NLog.dll", StringComparison.OrdinalIgnoreCase))
                    .Where(x => !x.Equals("NLog.UnitTests.dll", StringComparison.OrdinalIgnoreCase))
                    .Where(x => !x.Equals("NLog.Extended.dll", StringComparison.OrdinalIgnoreCase))
                    .Select(x => Path.Combine(assemblyLocation, x));

                InternalLogger.Debug("Start auto loading, location: {0}", assemblyLocation);
                foreach (var extensionDll in extensionDlls)
                {
                    InternalLogger.Info("Auto loading assembly file: {0}", extensionDll);
                    var success = false;
                    try
                    {
                        var extensionAssembly = Assembly.LoadFrom(extensionDll);
                        InternalLogger.LogAssemblyVersion(extensionAssembly);
                        factory.RegisterItemsFromAssembly(extensionAssembly);
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        if (ex.MustBeRethrownImmediately())
                        {
                            throw;
                        }

                        InternalLogger.Warn(ex, "Auto loading assembly file: {0} failed! Skipping this file.", extensionDll);
                        //TODO NLog 5, check MustBeRethrown()
                    }
                    if (success)
                    {
                        InternalLogger.Info("Auto loading assembly file: {0} succeeded!", extensionDll);
                    }

                }
            }
            catch (UnauthorizedAccessException ex)
            {
                InternalLogger.Warn(ex, "Seems that we do not have permission");
                if (ex.MustBeRethrown())
                {
                    throw;
                }
            }
            InternalLogger.Debug("Auto loading done");
#endif

            return factory;
        }
        static void InitNLogConfigurationItemFactory()
        {
            // Default initialization code for ConfigurationItemFactory.Default spends 
            // almost 0.5 sec in il-packed executable. (it scans whole types in assembly to find plugin types)
            // To avoid this slow-down, manual initialization is written.
            // If you need another layout-renderer, filter or anything else in NLog assembly,
            // please insert register code here.

            var factory = new ConfigurationItemFactory(new Assembly[0]);
            factory.LayoutRenderers.RegisterDefinition("longdate", typeof(LongDateLayoutRenderer));
            factory.LayoutRenderers.RegisterDefinition("level", typeof(LevelLayoutRenderer));
            factory.LayoutRenderers.RegisterDefinition("logger", typeof(LoggerNameLayoutRenderer));
            factory.LayoutRenderers.RegisterDefinition("message", typeof(MessageLayoutRenderer));
            factory.LayoutRenderers.RegisterDefinition("exception", typeof(ExceptionLayoutRenderer));
            factory.LayoutRenderers.RegisterDefinition("uppercase", typeof(UppercaseLayoutRendererWrapper));
            ConfigurationItemFactory.Default = factory;
        }
Beispiel #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConditionParser" /> class.
 /// </summary>
 /// <param name="expressionText">The expression text.</param>
 /// <param name="configurationItemFactory">Instance of <see cref="ConfigurationItemFactory"/> used to resolve references to condition methods and layout renderers.</param>
 private ConditionParser(string expressionText, ConfigurationItemFactory configurationItemFactory)
 {
     this.configurationItemFactory = configurationItemFactory;
     this.tokenizer = new ConditionTokenizer(expressionText ?? string.Empty);
 }
 /// <summary>
 /// Initializes static members of the <see cref="ConfigurationItemFactory"/> class.
 /// </summary>
 static ConfigurationItemFactory()
 {
     Default = new ConfigurationItemFactory(typeof(Logger).Assembly);
 }
Beispiel #14
0
 internal SimpleLayout(LayoutRenderer[] renderers, string text, ConfigurationItemFactory configurationItemFactory)
 {
     this.configurationItemFactory = configurationItemFactory;
     this.SetRenderers(renderers, text);
 }
Beispiel #15
0
 public LayoutRendererFactory(ConfigurationItemFactory parentFactory) : base(parentFactory)
 {
 }
Beispiel #16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConditionParser"/> class.
 /// </summary>
 /// <param name="stringReader">The string reader.</param>
 /// <param name="configurationItemFactory">Instance of <see cref="ConfigurationItemFactory"/> used to resolve references to condition methods and layout renderers.</param>
 private ConditionParser(SimpleStringReader stringReader, ConfigurationItemFactory configurationItemFactory)
 {
     this.configurationItemFactory = configurationItemFactory;
     this.tokenizer = new ConditionTokenizer(stringReader);
 }
Beispiel #17
0
 /// <summary>
 /// Parses the specified condition string and turns it into
 /// <see cref="ConditionExpression"/> tree.
 /// </summary>
 /// <param name="stringReader">The string reader.</param>
 /// <param name="configurationItemFactories">Instance of <see cref="ConfigurationItemFactory"/> used to resolve references to condition methods and layout renderers.</param>
 /// <returns>
 /// The root of the expression syntax tree which can be used to get the value of the condition in a specified context.
 /// </returns>
 internal static ConditionExpression ParseExpression(SimpleStringReader stringReader, ConfigurationItemFactory configurationItemFactories)
 {
     var parser = new ConditionParser(stringReader, configurationItemFactories);
     ConditionExpression expression = parser.ParseExpression();
 
     return expression;
 }
Beispiel #18
0
        /// <summary>
        /// Builds the default configuration item factory.
        /// </summary>
        /// <returns>Default factory.</returns>
        private static ConfigurationItemFactory BuildDefaultFactory()
        {
            var nlogAssembly = typeof(ILogger).Assembly;
            var factory      = new ConfigurationItemFactory(nlogAssembly);

            factory.RegisterExtendedItems();
#if !SILVERLIGHT
            try
            {
                var assemblyLocation = Path.GetDirectoryName(new Uri(nlogAssembly.CodeBase).LocalPath);
                if (assemblyLocation == null)
                {
                    InternalLogger.Warn("No auto loading because Nlog.dll location is unknown");
                    return(factory);
                }
                if (!Directory.Exists(assemblyLocation))
                {
                    InternalLogger.Warn("No auto loading because '{0}' doesn't exists", assemblyLocation);
                    return(factory);
                }

                var extensionDlls = Directory.GetFiles(assemblyLocation, "NLog*.dll")
                                    .Select(Path.GetFileName)
                                    .Where(x => !x.Equals("NLog.dll", StringComparison.OrdinalIgnoreCase))
                                    .Where(x => !x.Equals("NLog.UnitTests.dll", StringComparison.OrdinalIgnoreCase))
                                    .Where(x => !x.Equals("NLog.Extended.dll", StringComparison.OrdinalIgnoreCase))
                                    .Select(x => Path.Combine(assemblyLocation, x));

                InternalLogger.Debug("Start auto loading, location: {0}", assemblyLocation);
                foreach (var extensionDll in extensionDlls)
                {
                    InternalLogger.Info("Auto loading assembly file: {0}", extensionDll);
                    var success = false;
                    try
                    {
                        var extensionAssembly = Assembly.LoadFrom(extensionDll);
                        InternalLogger.LogAssemblyVersion(extensionAssembly);
                        factory.RegisterItemsFromAssembly(extensionAssembly);
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        if (ex.MustBeRethrownImmediately())
                        {
                            throw;
                        }

                        InternalLogger.Warn(ex, "Auto loading assembly file: {0} failed! Skipping this file.", extensionDll);
                        //TODO NLog 5, check MustBeRethrown()
                    }
                    if (success)
                    {
                        InternalLogger.Info("Auto loading assembly file: {0} succeeded!", extensionDll);
                    }
                }
            }
            catch (System.Security.SecurityException ex)
            {
                InternalLogger.Warn(ex, "Seems that we do not have permission");
                if (ex.MustBeRethrown())
                {
                    throw;
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                InternalLogger.Warn(ex, "Seems that we do not have permission");
                if (ex.MustBeRethrown())
                {
                    throw;
                }
            }
            InternalLogger.Debug("Auto loading done");
#endif

            return(factory);
        }
Beispiel #19
0
        public void MethodNameWithUnderscores()
        {
            var configurationItemFactory = new ConfigurationItemFactory();
            configurationItemFactory.LayoutRenderers.RegisterDefinition("foo", typeof(FooLayoutRenderer));
            configurationItemFactory.ConditionMethods.RegisterDefinition("__check__", typeof(MyConditionMethods).GetMethod("CheckIt"));

            ConditionParser.ParseExpression("__check__('${foo}')", configurationItemFactory);
        }
Beispiel #20
0
        public void CustomNLogFactoriesTest()
        {
            var configurationItemFactory = new ConfigurationItemFactory();
            configurationItemFactory.LayoutRenderers.RegisterDefinition("foo", typeof(FooLayoutRenderer));
            configurationItemFactory.ConditionMethods.RegisterDefinition("check", typeof(MyConditionMethods).GetMethod("CheckIt"));

            ConditionParser.ParseExpression("check('${foo}')", configurationItemFactory);
        }
Beispiel #21
0
        internal static LayoutRenderer[] CompileLayout(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr, bool isNested, out string text)
        {
            var result = new List<LayoutRenderer>();
            var literalBuf = new StringBuilder();

            int ch;

            int p0 = sr.Position;

            while ((ch = sr.Peek()) != -1)
            {
                if (isNested)
                {
                    //possible escape char `\` 
                    if (ch == '\\')
                    {
                        sr.Read();
                        var nextChar = sr.Peek();

                        //escape chars
                        if (nextChar == '}' || nextChar == ':')
                        {
                            //read next char and append
                            sr.Read();
                            literalBuf.Append((char)nextChar);
                        }
                        else
                        {
                            //dont treat \ as escape char and just read it
                            literalBuf.Append('\\');
                        }
                        continue;
                    }

                    if (ch == '}' || ch == ':')
                    {
                        //end of innerlayout. 
                        // `}` is when double nested inner layout. 
                        // `:` when single nested layout
                        break;
                    }
                }

                sr.Read();

                //detect `${` (new layout-renderer)
                if (ch == '$' && sr.Peek() == '{')
                {
                    //stach already found layout-renderer.
                    if (literalBuf.Length > 0)
                    {
                        result.Add(new LiteralLayoutRenderer(literalBuf.ToString()));
                        literalBuf.Length = 0;
                    }

                    LayoutRenderer newLayoutRenderer = ParseLayoutRenderer(configurationItemFactory, sr);
                    if (CanBeConvertedToLiteral(newLayoutRenderer))
                    {
                        newLayoutRenderer = ConvertToLiteral(newLayoutRenderer);
                    }

                    // layout renderer
                    result.Add(newLayoutRenderer);
                }
                else
                {
                    literalBuf.Append((char)ch);
                }
            }

            if (literalBuf.Length > 0)
            {
                result.Add(new LiteralLayoutRenderer(literalBuf.ToString()));
                literalBuf.Length = 0;
            }

            int p1 = sr.Position;

            MergeLiterals(result);
            text = sr.Substring(p0, p1);

            return result.ToArray();
        }
Beispiel #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SimpleLayout"/> class.
 /// </summary>
 /// <param name="txt">The layout string to parse.</param>
 /// <param name="configurationItemFactory">The NLog factories to use when creating references to layout renderers.</param>
 public SimpleLayout(string txt, ConfigurationItemFactory configurationItemFactory)
 {
     this.configurationItemFactory = configurationItemFactory;
     this.Text = txt;
 }
Beispiel #23
0
        public void CustomNotAgnosticTests()
        {
            var cif = new ConfigurationItemFactory();
            cif.RegisterType(typeof(CustomRendererNonAgnostic), string.Empty);
            var cfg = new LoggingConfiguration(cif);
            Layout l = new SimpleLayout("${customNotAgnostic}", cfg);

            l.Initialize(cfg);
            Assert.IsFalse(l.IsThreadAgnostic);
        }
 private static ConfigurationItemFactory SetupConditionMethods()
 {
     var factories = new ConfigurationItemFactory();
     factories.ConditionMethods.RegisterDefinition("GetGuid", typeof(MyConditionMethods).GetMethod("GetGuid"));
     factories.ConditionMethods.RegisterDefinition("ToInt16", typeof(MyConditionMethods).GetMethod("ToInt16"));
     factories.ConditionMethods.RegisterDefinition("ToInt32", typeof(MyConditionMethods).GetMethod("ToInt32"));
     factories.ConditionMethods.RegisterDefinition("ToInt64", typeof(MyConditionMethods).GetMethod("ToInt64"));
     factories.ConditionMethods.RegisterDefinition("ToDouble", typeof(MyConditionMethods).GetMethod("ToDouble"));
     factories.ConditionMethods.RegisterDefinition("ToSingle", typeof(MyConditionMethods).GetMethod("ToSingle"));
     factories.ConditionMethods.RegisterDefinition("ToDateTime", typeof(MyConditionMethods).GetMethod("ToDateTime"));
     factories.ConditionMethods.RegisterDefinition("ToDecimal", typeof(MyConditionMethods).GetMethod("ToDecimal"));
     factories.ConditionMethods.RegisterDefinition("IsValid", typeof(MyConditionMethods).GetMethod("IsValid"));
     return factories;
 }
        internal static LayoutRenderer[] CompileLayout(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr, bool isNested, out string text)
        {
            var result = new List<LayoutRenderer>();
            var literalBuf = new StringBuilder();

            int ch;

            int p0 = sr.Position;

            while ((ch = sr.Peek()) != -1)
            {
                if (isNested)
                {
                    //escape char? Then allow }, : and \
                    if (ch == '\\')
                    {
                        sr.Read();
                        var nextChar = sr.Peek();

                        //char that can be escaped.
                        if (nextChar == '}' || nextChar == ':' || nextChar == '\\')
                        {
                            //read next char and append
                            sr.Read();
                            literalBuf.Append((char)nextChar);
                        }
                        else
                        {
                            //dont read next char and just append the slash
                            literalBuf.Append('\\');
                        }
                        continue;
                    }

                    if (ch == '}' || ch == ':')
                    {
                        break;
                    }
                }

                sr.Read();

                if (ch == '$' && sr.Peek() == '{')
                {
                    if (literalBuf.Length > 0)
                    {
                        result.Add(new LiteralLayoutRenderer(literalBuf.ToString()));
                        literalBuf.Length = 0;
                    }

                    LayoutRenderer newLayoutRenderer = ParseLayoutRenderer(configurationItemFactory, sr);
                    if (CanBeConvertedToLiteral(newLayoutRenderer))
                    {
                        newLayoutRenderer = ConvertToLiteral(newLayoutRenderer);
                    }

                    // layout renderer
                    result.Add(newLayoutRenderer);
                }
                else
                {
                    literalBuf.Append((char)ch);
                }
            }

            if (literalBuf.Length > 0)
            {
                result.Add(new LiteralLayoutRenderer(literalBuf.ToString()));
                literalBuf.Length = 0;
            }

            int p1 = sr.Position;

            MergeLiterals(result);
            text = sr.Substring(p0, p1);

            return result.ToArray();
        }
        /// <summary>
        /// Builds the default configuration item factory.
        /// </summary>
        /// <returns>Default factory.</returns>
        private static ConfigurationItemFactory BuildDefaultFactory()
        {
            var factory = new ConfigurationItemFactory(typeof(Logger).Assembly);
            factory.RegisterExtendedItems();

            return factory;
        }
        public void CustomAgnosticTests()
        {
            var cif = new ConfigurationItemFactory();
            cif.RegisterType(typeof(CustomRendererAgnostic), string.Empty);

            Layout l = new SimpleLayout("${customAgnostic}", cif);

            l.Initialize(null);
            Assert.True(l.IsThreadAgnostic);
        }
Beispiel #28
0
 internal Factory(ConfigurationItemFactory parentFactory)
 {
     this.parentFactory = parentFactory;
 }
Beispiel #29
0
        private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr)
        {
            int ch = sr.Read();
            Debug.Assert(ch == '{', "'{' expected in layout specification");

            string name = ParseLayoutRendererName(sr);
            LayoutRenderer lr = configurationItemFactory.LayoutRenderers.CreateInstance(name);

            var wrappers = new Dictionary<Type, LayoutRenderer>();
            var orderedWrappers = new List<LayoutRenderer>();

            ch = sr.Read();
            while (ch != -1 && ch != '}')
            {
                string parameterName = ParseParameterName(sr).Trim();
                if (sr.Peek() == '=')
                {
                    sr.Read(); // skip the '='
                    PropertyInfo pi;
                    LayoutRenderer parameterTarget = lr;

                    if (!PropertyHelper.TryGetPropertyInfo(lr, parameterName, out pi))
                    {
                        Type wrapperType;

                        if (configurationItemFactory.AmbientProperties.TryGetDefinition(parameterName, out wrapperType))
                        {
                            LayoutRenderer wrapperRenderer;

                            if (!wrappers.TryGetValue(wrapperType, out wrapperRenderer))
                            {
                                wrapperRenderer = configurationItemFactory.AmbientProperties.CreateInstance(parameterName);
                                wrappers[wrapperType] = wrapperRenderer;
                                orderedWrappers.Add(wrapperRenderer);
                            }

                            if (!PropertyHelper.TryGetPropertyInfo(wrapperRenderer, parameterName, out pi))
                            {
                                pi = null;
                            }
                            else
                            {
                                parameterTarget = wrapperRenderer;
                            }
                        }
                    }

                    if (pi == null)
                    {
                        ParseParameterValue(sr);
                    }
                    else
                    {
                        if (typeof(Layout).IsAssignableFrom(pi.PropertyType))
                        {
                            var nestedLayout = new SimpleLayout();
                            string txt;
                            LayoutRenderer[] renderers = CompileLayout(configurationItemFactory, sr, true, out txt);

                            nestedLayout.SetRenderers(renderers, txt);
                            pi.SetValue(parameterTarget, nestedLayout, null);
                        }
                        else if (typeof(ConditionExpression).IsAssignableFrom(pi.PropertyType))
                        {
                            var conditionExpression = ConditionParser.ParseExpression(sr, configurationItemFactory);
                            pi.SetValue(parameterTarget, conditionExpression, null);
                        }
                        else
                        {
                            string value = ParseParameterValue(sr);
                            PropertyHelper.SetPropertyFromString(parameterTarget, parameterName, value, configurationItemFactory);
                        }
                    }
                }
                else
                {
                    // what we've just read is not a parameterName, but a value
                    // assign it to a default property (denoted by empty string)
                    PropertyInfo pi;

                    if (PropertyHelper.TryGetPropertyInfo(lr, string.Empty, out pi))
                    {
                        if (typeof(SimpleLayout) == pi.PropertyType)
                        {
                            pi.SetValue(lr, new SimpleLayout(parameterName), null);
                        }
                        else
                        {
                            string value = parameterName;
                            PropertyHelper.SetPropertyFromString(lr, pi.Name, value, configurationItemFactory);
                        }
                    }
                    else
                    {
                        InternalLogger.Warn("{0} has no default property", lr.GetType().FullName);
                    }
                }

                ch = sr.Read();
            }

            lr = ApplyWrappers(configurationItemFactory, lr, orderedWrappers);

            return lr;
        }
Beispiel #30
0
        private static bool TryNLogSpecificConversion(Type propertyType, string value, out object newValue, ConfigurationItemFactory configurationItemFactory)
        {
            if (propertyType == typeof(Layout) || propertyType == typeof(SimpleLayout))
            {
                newValue = new SimpleLayout(value, configurationItemFactory);
                return true;
            }

            if (propertyType == typeof(ConditionExpression))
            {
                newValue = ConditionParser.ParseExpression(value, configurationItemFactory);
                return true;
            }

            newValue = null;
            return false;
        }
Beispiel #31
0
        private static LayoutRenderer ApplyWrappers(ConfigurationItemFactory configurationItemFactory, LayoutRenderer lr, List<LayoutRenderer> orderedWrappers)
        {
            for (int i = orderedWrappers.Count - 1; i >= 0; --i)
            {
                var newRenderer = (WrapperLayoutRendererBase)orderedWrappers[i];
                InternalLogger.Trace("Wrapping {0} with {1}", lr.GetType().Name, newRenderer.GetType().Name);
                if (CanBeConvertedToLiteral(lr))
                {
                    lr = ConvertToLiteral(lr);
                }

                newRenderer.Inner = new SimpleLayout(new[] { lr }, string.Empty, configurationItemFactory);
                lr = newRenderer;
            }

            return lr;
        }