Esempio n. 1
0
        public void CustomNLogFactoriesTest()
        {
            var nlogFactories = new NLogFactories();
            nlogFactories.LayoutRendererFactory.RegisterDefinition("foo", typeof(FooLayoutRenderer));
            nlogFactories.ConditionMethodFactory.RegisterDefinition("check", typeof(MyConditionMethods).GetMethod("CheckIt"));

            var result = ConditionParser.ParseExpression("check('${foo}')", nlogFactories);
        }
Esempio n. 2
0
        internal static LayoutRenderer[] CompileLayout(NLogFactories nlogFactories, Tokenizer 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(nlogFactories, 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();
        }
Esempio n. 3
0
 /// <summary>
 /// Initializes static members of the NLogFactories class.
 /// </summary>
 static NLogFactories()
 {
     Default = new NLogFactories(typeof(Logger).Assembly);
 }
Esempio n. 4
0
 /// <summary>
 /// Implicitly converts the specified string to a <see cref="SimpleLayout"/>.
 /// </summary>
 /// <param name="layoutString">The layout string.</param>
 /// <param name="nlogFactories">The NLog factories to use when resolving layout renderers.</param>
 /// <returns>Instance of <see cref="SimpleLayout"/>.</returns>
 public static Layout FromString(string layoutString, NLogFactories nlogFactories)
 {
     return new SimpleLayout(layoutString, nlogFactories);
 }
Esempio n. 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="nlogFactories">Instance of <see cref="NLogFactories"/> 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, NLogFactories nlogFactories)
        {
            ConditionParser parser = new ConditionParser(expressionText, nlogFactories);
            ConditionExpression expression = parser.ParseExpression();
            if (!parser.tokenizer.IsEOF())
            {
                throw new ConditionParseException("Unexpected token: " + parser.tokenizer.TokenValue);
            }

            return expression;
        }
Esempio n. 6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConditionParser" /> class.
 /// </summary>
 /// <param name="expressionText">The expression text.</param>
 /// <param name="nlogFactories">Instance of <see cref="NLogFactories"/> used to resolve references to condition methods and layout renderers.</param>
 private ConditionParser(string expressionText, NLogFactories nlogFactories)
 {
     this.nlogFactories = nlogFactories;
     this.tokenizer.InitTokenizer(expressionText ?? string.Empty);
 }
Esempio n. 7
0
 private static NLogFactories SetupConditionMethods()
 {
     var factories = new NLogFactories();
     factories.ConditionMethodFactory.RegisterDefinition("GetGuid", typeof(MyConditionMethods).GetMethod("GetGuid"));
     factories.ConditionMethodFactory.RegisterDefinition("ToInt16", typeof(MyConditionMethods).GetMethod("ToInt16"));
     factories.ConditionMethodFactory.RegisterDefinition("ToInt32", typeof(MyConditionMethods).GetMethod("ToInt32"));
     factories.ConditionMethodFactory.RegisterDefinition("ToInt64", typeof(MyConditionMethods).GetMethod("ToInt64"));
     factories.ConditionMethodFactory.RegisterDefinition("ToDouble", typeof(MyConditionMethods).GetMethod("ToDouble"));
     factories.ConditionMethodFactory.RegisterDefinition("ToSingle", typeof(MyConditionMethods).GetMethod("ToSingle"));
     factories.ConditionMethodFactory.RegisterDefinition("ToDateTime", typeof(MyConditionMethods).GetMethod("ToDateTime"));
     factories.ConditionMethodFactory.RegisterDefinition("ToDecimal", typeof(MyConditionMethods).GetMethod("ToDecimal"));
     factories.ConditionMethodFactory.RegisterDefinition("IsValid", typeof(MyConditionMethods).GetMethod("IsValid"));
     return factories;
 }
Esempio n. 8
0
        public void LayoutRendererThrows()
        {
            NLogFactories nlogFactories = new NLogFactories();
            nlogFactories.LayoutRendererFactory.RegisterDefinition("throwsException", typeof(ThrowsExceptionRenderer));

            SimpleLayout l = new SimpleLayout("xx${throwsException}yy", nlogFactories);
            string output = l.Render(LogEventInfo.CreateNullEvent());
            Assert.AreEqual("xxyy", output);
        }
Esempio n. 9
0
        public void LayoutRendererThrows2()
        {
            string internalLogOutput = RunAndCaptureInternalLog(
                () =>
                    {
                        NLogFactories nlogFactories = new NLogFactories();
                        nlogFactories.LayoutRendererFactory.RegisterDefinition("throwsException", typeof(ThrowsExceptionRenderer));

                        SimpleLayout l = new SimpleLayout("xx${throwsException:msg1}yy${throwsException:msg2}zz", nlogFactories);
                        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);
        }
Esempio n. 10
0
        static int Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Usage: MakeNLogXSD outputfile.xsd path_to_doc.xml");
                return 1;
            }

            var factories = new NLogFactories();

            try
            {
                docXml.Load(args[1]);

                for (int i = 2; i < args.Length; ++i)
                {
                    try
                    {
                        Assembly asm = Assembly.Load(args[i]);
                        factories.RegisterItemsFromAssembly(asm, "");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("WARNING: {0}", ex.Message);
                    }
                }

                StringWriter sw = new StringWriter();

                sw.Write("<root xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">");

                XmlTextWriter xtw = new XmlTextWriter(sw);
                xtw.Namespaces = false;
                xtw.Formatting = Formatting.Indented;

                typeDumped[typeof(object)] = 1;
                typeDumped[typeof(Target)] = 1;
                typeDumped[typeof(TargetWithLayout)] = 1;
                typeDumped[typeof(TargetWithLayoutHeaderAndFooter)] = 1;
                typeDumped[typeof(Layout)] = 1;

                foreach (var target in factories.TargetFactory.AllRegisteredItems)
                {
                    DumpType(xtw, target.Value);
                }
                foreach (var filter in factories.FilterFactory.AllRegisteredItems)
                {
                    DumpType(xtw, filter.Value);
                }
                foreach (var layout in factories.LayoutFactory.AllRegisteredItems)
                {
                    DumpType(xtw, layout.Value);
                }
                xtw.Flush();
                sw.Write("</root>");
                sw.Flush();

                XmlDocument doc2 = new XmlDocument();
                doc2.LoadXml(sw.ToString());

                using (Stream templateStream = Assembly.GetEntryAssembly().GetManifestResourceStream("MakeNLogXSD.TemplateNLog.xsd"))
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(templateStream);

                    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                    nsmgr.AddNamespace("", "http://www.w3.org/2001/XMLSchema");

                    XmlNode n = doc.SelectSingleNode("//types-go-here");

                    foreach (XmlElement el in doc2.DocumentElement.ChildNodes)
                    {
                        XmlNode importedNode = doc.ImportNode(el, true);
                        n.ParentNode.InsertBefore(importedNode, n);
                    }
                    n.ParentNode.RemoveChild(n);

                    n = doc.SelectSingleNode("//filters-go-here");
                    foreach (var filter in factories.FilterFactory.AllRegisteredItems)
                    {
                        XmlElement el = doc.CreateElement("xs:element", XmlSchema.Namespace);
                        el.SetAttribute("name", filter.Key);
                        el.SetAttribute("type", SimpleTypeName(filter.Value));
                        n.ParentNode.InsertBefore(el, n);
                    }
                    n.ParentNode.RemoveChild(n);

                    Console.WriteLine("Saving schema to: {0}", args[0]);
                    doc.Save(args[0]);
                    return 0;
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: {0}", ex);
                return 1;
            }
        }
Esempio n. 11
0
        public void MethodNameWithUnderscores()
        {
            var nlogFactories = new NLogFactories();
            nlogFactories.LayoutRendererFactory.RegisterDefinition("foo", typeof(FooLayoutRenderer));
            nlogFactories.ConditionMethodFactory.RegisterDefinition("__check__", typeof(MyConditionMethods).GetMethod("CheckIt"));

            var result = ConditionParser.ParseExpression("__check__('${foo}')", nlogFactories);
        }
Esempio n. 12
0
 internal SimpleLayout(LayoutRenderer[] renderers, string text, NLogFactories nlogFactories)
 {
     this.nlogFactories = nlogFactories;
     this.SetRenderers(renderers, text);
 }
Esempio n. 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SimpleLayout"/> class.
 /// </summary>
 /// <param name="txt">The layout string to parse.</param>
 /// <param name="nlogFactories">The NLog factories to use when creating references to layout renderers.</param>
 public SimpleLayout(string txt, NLogFactories nlogFactories)
 {
     this.nlogFactories = nlogFactories;
     this.Text = txt;
 }
Esempio n. 14
0
        private static LayoutRenderer ParseLayoutRenderer(NLogFactories nlogFactories, Tokenizer sr)
        {
            int ch = sr.Read();
            Debug.Assert(ch == '{', "'{' expected in layout specification");

            string name = ParseLayoutRendererName(sr);
            LayoutRenderer lr = nlogFactories.LayoutRendererFactory.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 (nlogFactories.AmbientPropertyFactory.TryGetDefinition(parameterName, out wrapperType))
                        {
                            LayoutRenderer wrapperRenderer;

                            if (!wrappers.TryGetValue(wrapperType, out wrapperRenderer))
                            {
                                wrapperRenderer = nlogFactories.AmbientPropertyFactory.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(nlogFactories, sr, true, out txt);

                            nestedLayout.SetRenderers(renderers, txt);
                            pi.SetValue(parameterTarget, nestedLayout, null);
                        }
                        else
                        {
                            string value = ParseParameterValue(sr);
                            PropertyHelper.SetPropertyFromString(parameterTarget, parameterName, value, null);
                        }
                    }
                }
                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, null);
                        }
                    }
                    else
                    {
                        InternalLogger.Warn("{0} has no default property", lr.GetType().FullName);
                    }
                }

                ch = sr.Read();
            }

            lr = ApplyWrappers(nlogFactories, lr, orderedWrappers);

            return lr;
        }
Esempio n. 15
0
        private static LayoutRenderer ApplyWrappers(NLogFactories nlogFactories, 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, nlogFactories);
                lr = newRenderer;
            }

            return lr;
        }