Ejemplo n.º 1
0
        /// <summary>
        /// Creates logger by reflection for configured logger
        /// </summary>
        /// <returns></returns>
        private static ILogger InstantiateLogger(string loggerName)
        {
            if (string.IsNullOrEmpty(loggerName))
            {
                throw new ArgumentNullException("loggerName");
            }
            if (_loggers.ContainsKey(loggerName))
            {
                return(_loggers[loggerName]);
            }

            bool permanent = false;

            try
            {
                Type loggerType = typeof(SimpleLogImpl);
                if (Configuration != null)
                {
                    string typename = Configuration.defaultloggertype;

                    try
                    {
                        LoggerDefinition def = GetDefinition(loggerName);
                        if (!string.IsNullOrEmpty(def.type))
                        {
                            typename = def.type;
                        }
                        permanent = def.permanent;
                    }
                    catch (LogbusException)
                    {
                    }
                    catch (InvalidOperationException)
                    {
                    }

                    if (!string.IsNullOrEmpty(typename))
                    {
                        if (typename.IndexOf('.') < 0)
                        {
                            //This is probably a plain class name, overriding to It.Unina.Dis.Logbus.Loggers namespace
                            const string namespc      = "It.Unina.Dis.Logbus.Loggers";
                            string       assemblyname = typeof(LoggerHelper).Assembly.GetName().ToString();
                            typename = string.Format("{0}.{1}, {2}", namespc, typename, assemblyname);
                        }
                        loggerType = Type.GetType(typename);
                        if (!typeof(ILogger).IsAssignableFrom(loggerType))
                        {
                            LogbusConfigurationException ex =
                                new LogbusConfigurationException(
                                    "Registered logger type does not implement ILogger");
                            ex.Data.Add("type", loggerType);
                            throw ex;
                        }
                    }
                }
                ILogger ret = (ILogger)Activator.CreateInstance(loggerType);
                ret.LogName = loggerName;

                //Let's see if the collector name is well-known
                try
                {
                    WellKnownLogger knownLogger = (WellKnownLogger)Enum.Parse(typeof(WellKnownLogger), loggerName);
                    ret.HeartbeatInterval = 0;
                    switch (knownLogger)
                    {
                    case WellKnownLogger.Logbus:
                    {
                        ret.Facility = SyslogFacility.Internally;
                        break;
                    }

                    case WellKnownLogger.CollectorInternal:
                    {
                        ret.Facility = SyslogFacility.Internally;
                        break;
                    }

                    case WellKnownLogger.Client:
                    {
                        ret.Facility = SyslogFacility.Local5;
                        break;
                    }
                    }
                }
                catch (ArgumentException)
                {
                }

                if (permanent)
                {
                    _loggers.Add(loggerName, ret);
                }
                return(ret);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Unable to create logger because of configuration error", ex);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Parse a text file and build a configuration instance
        /// </summary>
        /// <returns>The parsed instance.</returns>
        /// <param name="path">The path to the file to read.</param>
        public static CLIServerConfiguration ParseTextFile(string path)
        {
            var cfg  = new CLIServerConfiguration();
            var line = string.Empty;
            var re   = new System.Text.RegularExpressions.Regex(@"(?<comment>\#.*)|(\""(?<value>[^\""]*)\"")|((?<value>[^ ]*))");

            var s1names = BuildPropertyMap <CLIServerConfiguration>();
            var s2names = BuildPropertyMap <ServerConfig>();

            var lineindex = 0;
            Dictionary <string, string> lastitemprops = null;

            using (var fs = File.OpenRead(path))
                using (var sr = new StreamReader(fs, System.Text.Encoding.UTF8, true))
                    while ((line = sr.ReadLine()) != null)
                    {
                        var args = re.Matches(line)
                                   .Cast <System.Text.RegularExpressions.Match>()
                                   .Where(x => x.Groups["value"].Success && !string.IsNullOrWhiteSpace(x.Value))
                                   .Select(x => x.Groups["value"].Value)
                                   .ToArray();
                        lineindex++;
                        if (args.Length == 0)
                        {
                            continue;
                        }

                        var cmd = args.First();
                        if (s1names.ContainsKey(cmd))
                        {
                            if (args.Length > 2)
                            {
                                throw new Exception($"Too many arguments in line {lineindex}: {line}");
                            }
                            SetProperty(cfg, s1names[cmd], args.Skip(1).FirstOrDefault());
                        }
                        else if (s2names.ContainsKey(cmd))
                        {
                            if (args.Length > 2)
                            {
                                throw new Exception($"Too many arguments in line {lineindex}: {line}");
                            }

                            cfg.ServerOptions[cmd] = args.Skip(1).FirstOrDefault();
                        }
                        else if (string.Equals(cmd, "route", StringComparison.OrdinalIgnoreCase))
                        {
                            if (args.Length == 2)
                            {
                                var route = new RouteDefinition()
                                {
                                    Assembly = args.Skip(1).First()
                                };
                                cfg.Routes.Add(route);
                                lastitemprops = route.Options;
                            }
                            else
                            {
                                if (args.Length < 3)
                                {
                                    throw new Exception($"Too few arguments in line {lineindex}: {line}");
                                }

                                var route = new RouteDefinition()
                                {
                                    Assembly             = args.Skip(1).First(),
                                    Classname            = args.Skip(2).First(),
                                    ConstructorArguments = args.Skip(3).ToList()
                                };

                                cfg.Routes.Add(route);
                                lastitemprops = route.Options;
                            }
                        }
                        else if (string.Equals(cmd, "handler", StringComparison.OrdinalIgnoreCase))
                        {
                            if (args.Length < 3)
                            {
                                throw new Exception($"Too few arguments in line {lineindex}: {line}");
                            }

                            var route = new RouteDefinition()
                            {
                                RoutePrefix          = args.Skip(1).First(),
                                Classname            = args.Skip(2).First(),
                                ConstructorArguments = args.Skip(3).ToList()
                            };

                            cfg.Routes.Add(route);
                            lastitemprops = route.Options;
                        }
                        else if (string.Equals(cmd, "module", StringComparison.OrdinalIgnoreCase))
                        {
                            if (args.Length < 2)
                            {
                                throw new Exception($"Too few arguments in line {lineindex}: {line}");
                            }

                            var module = new ModuleDefinition()
                            {
                                Classname            = args.Skip(1).First(),
                                ConstructorArguments = args.Skip(2).ToList()
                            };

                            cfg.Modules.Add(module);
                            lastitemprops = module.Options;
                        }
                        else if (string.Equals(cmd, "postprocessor", StringComparison.OrdinalIgnoreCase))
                        {
                            if (args.Length < 2)
                            {
                                throw new Exception($"Too few arguments in line {lineindex}: {line}");
                            }

                            var postprocessor = new PostProcessorDefinition()
                            {
                                Classname            = args.Skip(1).First(),
                                ConstructorArguments = args.Skip(2).ToList()
                            };

                            cfg.PostProcessors.Add(postprocessor);
                            lastitemprops = postprocessor.Options;
                        }

                        else if (string.Equals(cmd, "logger", StringComparison.OrdinalIgnoreCase))
                        {
                            if (args.Length < 2)
                            {
                                throw new Exception($"Too few arguments in line {lineindex}: {line}");
                            }

                            var logger = new LoggerDefinition()
                            {
                                Classname            = args.Skip(1).First(),
                                ConstructorArguments = args.Skip(2).ToList()
                            };

                            cfg.Loggers.Add(logger);
                            lastitemprops = logger.Options;
                        }
                        else if (string.Equals(cmd, "set", StringComparison.OrdinalIgnoreCase))
                        {
                            if (lastitemprops == null)
                            {
                                throw new Exception($"There was no active entry to set properties for in line {lineindex}");
                            }

                            if (args.Length > 3)
                            {
                                throw new Exception($"Too many arguments in line {lineindex}: {line}");
                            }
                            if (args.Length < 2)
                            {
                                throw new Exception($"Too few arguments in line {lineindex}: {line}");
                            }

                            lastitemprops[args.Skip(1).First()] = args.Skip(2).FirstOrDefault();
                        }
                        else if (string.Equals(cmd, "serve", StringComparison.OrdinalIgnoreCase))
                        {
                            if (args.Length < 3)
                            {
                                throw new Exception($"Too few arguments in line {lineindex}: {line}");
                            }
                            if (args.Length > 3)
                            {
                                throw new Exception($"Too many arguments in line {lineindex}: {line}");
                            }

                            var routearg = args.Skip(1).First();
                            if (routearg == string.Empty)
                            {
                                routearg = "/";
                            }

                            if (!routearg.StartsWith("/", StringComparison.Ordinal))
                            {
                                throw new Exception($"The route must start with a forward slash in line {lineindex}: {line}");
                            }
                            while (routearg.Length > 1 && routearg.EndsWith("/", StringComparison.Ordinal))
                            {
                                routearg = routearg.Substring(0, routearg.Length - 1);
                            }

                            var pathprefix = routearg;

                            routearg = routearg == "/" ? "[/.*]" : $"[{routearg}(/.*)?]";

                            var route = new RouteDefinition()
                            {
                                RoutePrefix          = routearg,
                                Classname            = typeof(Ceen.Httpd.Handler.FileHandler).AssemblyQualifiedName,
                                ConstructorArguments = args.Skip(2).ToList()
                            };

                            cfg.Routes.Add(route);
                            lastitemprops = route.Options;
                            lastitemprops.Add(nameof(Ceen.Httpd.Handler.FileHandler.PathPrefix), pathprefix);
                        }
                        else if (string.Equals(cmd, "redirect", StringComparison.OrdinalIgnoreCase))
                        {
                            if (args.Length < 3)
                            {
                                throw new Exception($"Too few arguments in line {lineindex}: {line}");
                            }
                            if (args.Length > 3)
                            {
                                throw new Exception($"Too many arguments in line {lineindex}: {line}");
                            }

                            var routearg = args.Skip(1).First();

                            var route = new RouteDefinition()
                            {
                                RoutePrefix          = routearg,
                                Classname            = typeof(Ceen.Httpd.Handler.RedirectHandler).AssemblyQualifiedName,
                                ConstructorArguments = args.Skip(2).ToList()
                            };

                            cfg.Routes.Add(route);
                            lastitemprops = route.Options;
                        }
                        else if (string.Equals(cmd, "mime", StringComparison.OrdinalIgnoreCase))
                        {
                            if (args.Length < 3)
                            {
                                throw new Exception($"Too few arguments in line {lineindex}: {line}");
                            }
                            if (args.Length > 3)
                            {
                                throw new Exception($"Too many arguments in line {lineindex}: {line}");
                            }

                            var key = args.Skip(1).First();
                            if (!string.IsNullOrEmpty(key) && key != "*" && !key.StartsWith(".", StringComparison.Ordinal))
                            {
                                key = "." + key;
                            }

                            cfg.MimeTypes[key] = args.Skip(2).First();
                        }
                        else if (string.Equals(cmd, "header", StringComparison.OrdinalIgnoreCase))
                        {
                            if (args.Length < 3)
                            {
                                throw new Exception($"Too few arguments in line {lineindex}: {line}");
                            }
                            if (args.Length > 3)
                            {
                                throw new Exception($"Too many arguments in line {lineindex}: {line}");
                            }

                            cfg.DefaultHeaders[args.Skip(1).First()] = args.Skip(2).First();
                        }
                        else if (string.Equals(cmd, "index", StringComparison.OrdinalIgnoreCase))
                        {
                            if (args.Length < 2)
                            {
                                throw new Exception($"Too few arguments in line {lineindex}: {line}");
                            }
                            if (args.Length > 2)
                            {
                                throw new Exception($"Too many arguments in line {lineindex}: {line}");
                            }

                            cfg.IndexDocuments.Add(args.Skip(1).First());
                        }
                        else
                        {
                            throw new Exception($"Unable to parse the action \"{cmd}\" for line {lineindex}: \"{line}\"");
                        }
                    }


            cfg.Basepath     = Path.GetFullPath(cfg.Basepath ?? ".");
            cfg.Assemblypath = string.Join(Path.PathSeparator.ToString(), (cfg.Assemblypath ?? "").Split(new char[] { Path.PathSeparator }).Select(x => Path.GetFullPath(Path.Combine(cfg.Basepath, ExpandEnvironmentVariables(x)))));

            return(cfg);
        }
Ejemplo n.º 3
0
        public void FFDATest()
        {
            FilterBase ffda_filter =
                new FacilityEqualsFilter()
            {
                facility = SyslogFacility.Local0
            } &
            new PropertyFilter()
            {
                comparison = ComparisonOperator.eq, propertyName = Property.MessageID, value = "FFDA"
            };

            StringBuilder markup = new StringBuilder();

            new XmlSerializer(typeof(FilterBase)).Serialize(XmlTextWriter.Create(markup, new XmlWriterSettings()
            {
                Indent = true
            }), ffda_filter, ffda_filter.xmlns);

            TestContext.WriteLine("{0}", markup.ToString());

            const int SEND_PORT = 5427;

            //Init Logbus
            LogbusServerConfiguration core_config = new LogbusServerConfiguration();

            core_config.corefilter = ffda_filter;
            InboundChannelDefinition in_ch = new InboundChannelDefinition();

            in_ch.type  = "SyslogUdpReceiver";
            in_ch.param = new KeyValuePair[]
            {
                new KeyValuePair()
                {
                    name  = "port",
                    value = SEND_PORT.ToString()
                }
            };
            core_config.inchannels = new InboundChannelDefinition[] { in_ch };

            using (ILogBus logbus = new LogbusService(core_config))
            {
                logbus.MessageReceived += new EventHandler <SyslogMessageEventArgs>(logbus_MessageReceived);
                logbus.Start();

                //Init FFDA
                LogbusLoggerConfiguration source_config = new LogbusLoggerConfiguration();
                LoggerDefinition          udp_def       = new LoggerDefinition()
                {
                    type  = "SyslogUdpCollector",
                    param = new KeyValuePair[] { new KeyValuePair()
                                                 {
                                                     name = "port", value = SEND_PORT.ToString()
                                                 }, new KeyValuePair()
                                                 {
                                                     name = "ip", value = "127.0.0.1"
                                                 } }
                };
                source_config.logger       = new LoggerDefinition[] { udp_def };
                LoggerHelper.Configuration = source_config;

                //Send what we want: 2 FFDA messages
                IFieldFailureDataLogger logger = FieldFailureDataHelper.CreateFailureDataLogger("ffda");
                logger.LogSST();
                logger.LogSEN();

                //Send junk
                ILog junk_log = LoggerHelper.GetLogger();
                junk_log.Debug("Hello");
                junk_log.Error("Junk error");

                Thread.Sleep(1000);
                logbus.Stop();
            }

            Assert.AreEqual(2, messages);
        }