예제 #1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // gather log4net output with small hack to get results...
        ILoggerRepository repository = LogManager.GetRepository();

        IAppender[]    appenders = repository.GetAppenders();
        MemoryAppender appender  = null;

        foreach (IAppender a in appenders)
        {
            if (a is MemoryAppender)
            {
                // we found our appender to look results from
                appender = a as MemoryAppender;
                break;
            }
        }

        if (appender != null)
        {
            appender.Clear();
            fulfillmentService.ProcessCustomer(customerEditController.CurrentCustomer.Id);
            LoggingEvent[] events       = appender.GetEvents();
            StringWriter   stringWriter = new StringWriter();
            PatternLayout  layout       = new PatternLayout("%date{HH:mm:ss} %-5level %logger{1}: %message<br />");
            foreach (LoggingEvent loggingEvent in events)
            {
                layout.Format(stringWriter, loggingEvent);
            }

            results.Text = stringWriter.ToString();
        }
    }
예제 #2
0
파일: Program.cs 프로젝트: xxzztt/Demo
 private static void InitLog4Net()
 {
     XmlConfigurator.ConfigureAndWatch(
         new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config")));
     _log4NetKeepFalse = LogManager.GetLogger("keepfalse");
     _log4NetKeepTrue  = LogManager.GetLogger("keeptrue");
 }
예제 #3
0
        private ILog GetLog4NetLogger()
        {
            BasicConfigurator.Configure();

            // from https://stackoverflow.com/questions/16336917/can-you-configure-log4net-in-code-instead-of-using-a-config-file
            var hierarchy = (Hierarchy)LogManager.GetRepository();

            hierarchy.ResetConfiguration();
            hierarchy.Clear();

            var patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "%date [%thread] %-5level %logger %message%newline";
            patternLayout.ActivateOptions();

            var roller = new RollingFileAppender();

            roller.AppendToFile   = false;
            roller.File           = $"{_logsFolder}/log4net.txt";
            roller.Layout         = patternLayout;
            roller.ImmediateFlush = true;
            roller.RollingStyle   = RollingFileAppender.RollingMode.Once;
            roller.MaxFileSize    = 128 * 1000 * 1000;
            roller.ActivateOptions();

            hierarchy.Threshold  = Level.Info;
            hierarchy.Root.Level = Level.Info;
            hierarchy.Root.AddAppender(roller);

            hierarchy.Configured = true;

            return(LogManager.GetLogger(GetType()));
        }
예제 #4
0
        public static void Initialize()
        {
            //foreach(var assemb in AppDomain.CurrentDomain.GetAssemblies())
            var repo = LogManager.GetRepository(Assembly.GetEntryAssembly());

            (((log4net.Repository.Hierarchy.Hierarchy)repo)).Root.Level = Level.All;
            (((log4net.Repository.Hierarchy.Hierarchy)repo)).RaiseConfigurationChanged(EventArgs.Empty);
            BasicConfigurator.Configure(repo, new NLogAppender());
        }
예제 #5
0
 public static void ShutDown()
 {
     Debug("Application + Logging ShutDown");
     lock (log4net_loaded_lock)
     {
         log4net_has_shutdown = true;
         __log = null;
     }
     LogManager.Flush(5000);
     LogManager.Shutdown();
 }
예제 #6
0
        private void ConfigurateLogging()
        {
            Uri configUri = new Uri($"{AppDomain.CurrentDomain.BaseDirectory}config/logconfig.xml");

            if (!File.Exists(configUri.OriginalString))
            {
                throw new ConfigNotExistsException($"configuration file not found at: {configUri.AbsolutePath}");
            }

            XmlConfigurator.Configure(configUri);
            LogManager.GetLogger(typeof(Bootstrapper)).Info("Logging configurated in Bootstrapper");
        }
예제 #7
0
        public void Cleanup()
        {
            LogManager.Shutdown();
            NLog.LogManager.Configuration = null;

            foreach (var directoryInfo in Folders)
            {
                directoryInfo.Delete(true);
            }

            Folders.Clear();
        }
예제 #8
0
        public static string GetLogFilename()
        {
            foreach (var logger in LogManager.GetRepository().GetAppenders())
            {
                RollingFileAppender rfa = logger as RollingFileAppender;
                if (null != rfa)
                {
                    return(rfa.File);
                }
            }

            return(null);
        }
예제 #9
0
 public static void Verify()
 {
     if (!LogManagerLog4net.GetRepository().Configured)
     {
         // log4net not configured
         foreach (
             LogLog message in
             LogManagerLog4net.GetRepository().ConfigurationMessages.Cast <LogLog>())
         {
             // evaluate configuration message
             var m = message;
         }
     }
 }
        public HttpConfiguration Build()
        {
            var logger       = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            var commonLogger = new CodeConfigurableLog4NetLogger(logger);

            IList <Func <string, ScriptClass> > typeStrategies = new List <Func <string, ScriptClass> >(_typeStrategies);
            var services = new ScriptServicesBuilder(new ScriptConsole(), commonLogger).
                           FilePreProcessor <WebApiFilePreProcessor>().Build();

            var preProcessor = (WebApiFilePreProcessor)services.FilePreProcessor;

            typeStrategies.Add(ControllerStategy);
            preProcessor.SetClassStrategies(typeStrategies);
            preProcessor.LoadSharedCode(Path.Combine(_scriptsPath, "Shared"));
            ProcessScripts(services);
            return(_configuration);
        }
예제 #11
0
        public void Initialize()
        {
            if (!initialized)
            {
                initialized = true;
            }
            else
            {
                return;
            }

            if (File.Exists("Log.txt"))
            {
                File.Delete("Log.txt");
            }

            logWriter  = File.CreateText("Log.txt");
            logBuilder = new StringBuilder();
            logger     = LogglyManager.GetLogger("ConfigEditor");
        }
예제 #12
0
        public ClipboardViewModel(IEventAggregator eventAggregator, ClipboardRepo clipboardRepo)
        {
            _logger          = LogManager.GetLogger("ClipboardViewModel");
            _eventAggregator = eventAggregator;
            _clipboardRepo   = clipboardRepo;
            _eventAggregator.Subscribe(this);
            DisplayName = "Clipboard";

            ClipboardItems = new BindableCollection <ClipboardItemViewModel>();

            _masterList = new List <ClipboardItemViewModel>();

            HideStateMsg = false;

            var clipboardItems = LoadClipboardItems();

            _masterList.AddRange(clipboardItems);

            SafeAddToClipboardHistory(BuildViewModelFromClipboard());
            RebuildClipboardItems();

            HideStateMsg = true;
        }
 /// <summary>
 /// Gets the Logger and overgive a filename
 /// </summary>
 /// <param name="filename"></param>
 /// <returns></returns>
 public static ILog GetLogger([CallerFilePath] string filename = "")
 {
     return(LogManager.GetLogger(filename));
 }
예제 #14
0
        /// <summary>
        /// Test whether the log4net-based log system has been loaded and set up and if so, enable the use of that logging system.
        ///
        /// Up to that moment, all Logging APIs will log to a memory buffer/queue which will written to the logging system
        /// once it is loaded, set up and active.
        /// </summary>
        public static void TriggerInit()
        {
            bool go;

            lock (log4net_loaded_lock)
            {
                go = (null == __log && !log4net_loaded && !log4net_init_pending && !log4net_has_shutdown);
                if (go)
                {
                    log4net_init_pending = true; // block simultaneous execution of the rest of the code in TriggerInit()
                }
            }

            if (go)
            {
                bool we_are_ready_for_the_next_phase = false;
                try
                {
                    // test if log4net assembly is loaded and ready:
                    Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
                    bool       active     = false;

                    foreach (Assembly assembly in assemblies)
                    {
                        if (assembly.FullName.StartsWith("log4net"))
                        {
                            active = true;
                            break;
                        }
                    }

                    if (active)
                    {
                        // as per https://stackoverflow.com/questions/28723920/check-whether-log4net-xmlconfigurator-succeeded
                        //
                        // log4net must have picked up the configuration or it will not function anyhow
                        if (!LogManager.GetRepository().Configured)
                        {
                            // log4net not configured
                            foreach (var message in LogManager.GetRepository().ConfigurationMessages)
                            {
                                // evaluate configuration message
                                LogLog logInitMsg = message as LogLog;
                                BufferMessage(String.Format("log config: {0}", logInitMsg?.Message ?? message));
                            }
                        }

                        we_are_ready_for_the_next_phase = true;
                    }
                }
                finally
                {
                    // make sure the pending flag is reset whenever we leave this block
                    lock (log4net_loaded_lock)
                    {
                        log4net_loaded = we_are_ready_for_the_next_phase;

                        log4net_init_pending = false; // de-block
                    }
                }
            }
        }
예제 #15
0
 public ILogger Create <T>()
 {
     return(new Log4NetLogger(LogManager.GetLogger(typeof(T))));
 }
예제 #16
0
        private static bool Init()
        {
            bool go;

            lock (log4net_loaded_lock)
            {
                go = (null == __log && log4net_loaded && !log4net_init_pending && !log4net_has_shutdown);
                if (go)
                {
                    log4net_init_pending = true; // block simultaneous execution of the rest of the code in Init()
                }
            }

            if (go)
            {
                try
                {
                    BasicConfigurator.Configure();
                    XmlConfigurator.Configure();
                    ILog l = LogManager.GetLogger(typeof(Logging));
                    lock (log4net_loaded_lock)
                    {
                        __log = l;
                    }
                    // as per https://stackoverflow.com/questions/28723920/check-whether-log4net-xmlconfigurator-succeeded
                    //
                    // log4net must have picked up the configuration or it will not function anyhow
                    //if (!LogManager.GetRepository().Configured)
                    {
                        // log4net not configured
                        foreach (var message in LogManager.GetRepository().ConfigurationMessages)
                        {
                            // evaluate configuration message
                            LogLog logInitMsg = message as LogLog;
                            BufferMessage(String.Format("log4net config: {0}", logInitMsg?.Message ?? message));
                        }
                    }
                }
                catch (Exception ex)
                {
                    BufferException(ex);
                }
            }

            bool rv;

            lock (log4net_loaded_lock)
            {
                if (go)
                {
                    log4net_init_pending = false; // de-block
                }
                // return value: TRUE when success
                rv = (null != __log);
            }

            // only log/yak about initialization success when it actually did happen just above:
            if (rv)
            {
                Debug("Logging initialised at {0}", LogAssist.AppendStackTrace(null, "get_log"));
                Info("Logging initialised.");

                // thread safety: move and reset the pending message buffer/list
                List <LogBufEntry> lst = new List <LogBufEntry>();
                lock (log4net_loaded_lock)
                {
                    if (init_ex_list != null && init_ex_list.Count > 0)
                    {
                        // move list
                        lst          = init_ex_list;
                        init_ex_list = null;
                    }
                }
                if (lst.Count > 0)
                {
                    Error("--- Logging early bird log messages: ---");
                    foreach (LogBufEntry ex in lst)
                    {
                        if (ex.ex != null)
                        {
                            if (ex.message != null)
                            {
                                Error(ex.ex, "{0}", ex.message);
                            }
                            else
                            {
                                Error(ex.ex, "Logger init failure?");
                            }
                        }
                        else
                        {
                            Info("{0}", ex.message);
                        }
                    }
                    lst.Clear();
                    Error("-- Logging early bird log messages done. ---");
                }
            }

            return(rv);
        }
예제 #17
0
        //static Log4netLogFactory()
        //{
        //    // load the log4net configuration from the application configuration.
        //    XmlConfigurator.Configure();
        //}

        public ILog GetLog(string name)
        {
            return(new Log4netLog(LogManager.GetLogger(name)));
        }
예제 #18
0
 public ILogger Create(Type type)
 {
     return(new Log4NetLogger(LogManager.GetLogger(type)));
 }
예제 #19
0
 public ILogger Create(string name)
 {
     return(new Log4NetLogger(LogManager.GetLogger(name)));
 }
예제 #20
0
 public override void Load()
 {
     this.Bind <ILog>().ToMethod(context => LogManagerLog4net.GetLogger(context.Request.Target.Member.ReflectedType));
     this.Bind(typeof(IRepository <>)).To(typeof(Repository <>));
 }
예제 #21
0
 public ILogger LoggerFor(Type type)
 {
     return(GetLogger(LogManager.GetLogger(type)));
 }
예제 #22
0
        public static int Main(string[] args)
        {
            //по умолчанию у gui приложения нет консоли, но если кто то запустил из консоли
            //то нужно с ним говорить
            //если делать это позже то вызов не дает результата
            AttachConsole(ATTACH_PARENT_PROCESS);
            SingleInstance instance    = null;
            var            help        = false;
            var            version     = false;
            var            quiet       = false;
            var            faultInject = false;
            var            debugpipe   = "";
            var            debug       = new List <string>();
            var            console     = false;
            var            encoding    = "";
            int            result;

            try {
                //проверка для ilmerge
                var merged = new [] {
                    "Caliburn.Micro", "Xceed.Wpf.Toolkit", "System.Windows.Interactivity", "log4net",
                    "Devart.Data", "Devart.Data.MySql",
                    "WpfAnimatedGif",
                    "AnalitF.Net.Client"
                };
                AppDomain.CurrentDomain.AssemblyResolve += (sender, eventArgs) => {
                    var name = new AssemblyName(eventArgs.Name);
                    if (merged.Any(n => name.Name.Equals(n, StringComparison.CurrentCultureIgnoreCase)))
                    {
                        return(typeof(Program).Assembly);
                    }
                    return(null);
                };

                var logConfig = new FileInfo(FileHelper.MakeRooted("log4net.config"));
                if (logConfig.Exists)
                {
                    XmlConfigurator.Configure(logConfig);
                }
                else
                {
                    XmlConfigurator.Configure();
                }

                string batchFile   = null;
                var    migrate     = false;
                var    firstChance = false;
                var    options     = new OptionSet {
                    { "help", "Показать справку", v => help = v != null },
                    { "version", "Показать информацию о версии", v => version = v != null },
                    { "quiet", "Не выводить предупреждения при запуске", v => quiet = v != null },
                    { "console", v => console = v != null },
                    { "encoding=", v => encoding = v },
                    { "debug=", v => debug.Add(v) },
                    { "first-chance", v => firstChance = v != null },
                    { "batch=", "Запустить приложение и вызвать автозаказ с указанным файлом", v => batchFile = v },
                    { "i", "", v => migrate = true },
#if DEBUG
                    { "fault-inject", "", v => faultInject = v != null },
                    { "debug-pipe=", "", v => debugpipe = v },
#endif
                };
                var cmds = options.Parse(args);

                if (firstChance)
                {
                    AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) => {
                        Log.Error(new StackTrace());
                        Log.Error("FirstChanceException", eventArgs.Exception);
                    };
                }
                //при определения установлен ли .net могла произойти ошибка и мы решили что .net установлен но на самом деле нет
                //или человек мог сменить компьютер
                //в этом случае при первом запуске с ключом миграции приложение свалится, и человек получит предложение установить .net
                //если он его установит то при последующем запуске мы должны понять что нужно импортировать данные
                var files = new [] { "Params.txt", "Password.txt", "GlobalParams.txt" };
                if (files.All(x => File.Exists(FileHelper.MakeRooted(x))))
                {
                    migrate = true;
                }
                if (migrate)
                {
                    cmds = new List <string> {
                        "migrate"
                    }
                }
                ;

                if (!String.IsNullOrEmpty(encoding))
                {
                    Console.OutputEncoding = Encoding.GetEncoding(encoding);
                }

                if (help)
                {
                    options.WriteOptionDescriptions(Console.Out);
                    return(0);
                }

                if (version)
                {
                    var assembly = typeof(Program).Assembly;
                    var hash     = assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false)
                                   .OfType <AssemblyCopyrightAttribute>()
                                   .Select(a => a.Copyright)
                                   .FirstOrDefault();
                    Console.WriteLine(assembly.GetName().Version);
                    Console.WriteLine(hash);
                    return(0);
                }

                var repository = (Hierarchy)LogManager.GetRepository();
                if (console)
                {
                    if (!repository.GetAppenders().OfType <ConsoleAppender>().Any())
                    {
                        var layout = new PatternLayout("%d{dd.MM.yyyy HH:mm:ss.fff} [%t] %-5p %c - %m%n");
                        layout.ActivateOptions();
                        var consoleAppender = new ConsoleAppender();
                        consoleAppender.Layout = layout;
                        consoleAppender.ActivateOptions();
                        repository.Root.AddAppender(consoleAppender);
                    }
                }

                foreach (var loggername in debug)
                {
                    var logger = (Logger)repository.GetLogger(loggername);
                    logger.Level = Level.Debug;
                }

                Log.InfoFormat("Приложение запущено {0}", typeof(Program).Assembly.Location);
                try {
                    Log.InfoFormat("Версия операционной системы {0}", Environment.OSVersion);
                    Log.InfoFormat("Версия среды выполнения {0}", Environment.Version);
                }
                catch (Exception e) {
                    Log.Error("Не удалось получить информацию о версии среды или ос", e);
                }
                Log.Logger.Repository.RendererMap.Put(typeof(Exception), new ExceptionRenderer());
                instance = new SingleInstance(typeof(AppBootstrapper).Assembly.GetName().Name);
                if (!instance.TryStart())
                {
                    return(0);
                }

                PlatformEnlightenmentProvider.Current = new RxProvider();
                //регистрация объектов reactiveui в нормальной жизни это должно произойти автоматический
                //но после ilmerge логика регистрации будет сломана
                new ReactiveUI.Routing.ServiceLocationRegistration().Register();
                new ReactiveUI.Xaml.ServiceLocationRegistration().Register();

                RxApp.MessageBus.Listen <string>()
                .Where(m => m == "Startup")
                .Subscribe(_ => instance.SignalStartup());

                RxApp.MessageBus.Listen <string>()
                .Where(m => m == "Shutdown")
                .Subscribe(_ => instance.SignalShutdown());

                var splash = new SplashScreen(@"assets/images/splash.png");
                if (!quiet)
                {
                    try {
                        splash.Show(true);
                    }
                    catch (Exception e) {
                        Log.Error("Ошибка при отображение заставки", e);
                    }
                }

                instance.Wait();

                var app = new App {
                    Splash      = splash,
                    FaultInject = faultInject
                };
                app.InitializeComponent();

                var bootstapper = new AppBootstrapper();
                bootstapper.Config.Quiet         = quiet;
                bootstapper.Config.DebugPipeName = debugpipe;
                bootstapper.Config.Cmd           = cmds.FirstOrDefault();
                if (!String.IsNullOrEmpty(batchFile))
                {
                    bootstapper.Config.Cmd = "batch=" + batchFile;
                }
                bootstapper.Start();
                result = app.Run();
                Log.InfoFormat("Приложение завершено");
            }
            catch (OptionException e) {
                result = 1;
                Console.WriteLine(e.Message);
            }
            catch (Exception e) {
                var message = e is EndUserError ? e.Message : e.ToString();
                result = 1;
                Console.WriteLine(message);
                Log.Error("Ошибка при запуске приложения", e);
                if (!quiet)
                {
                    MessageBox.Show(
                        message,
                        "АналитФАРМАЦИЯ: Внимание",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error);
                }
            }
            finally {
                instance?.SignalShutdown();
            }

            return(result);
        }
예제 #23
0
 public LoggerControl()
 {
     Log    = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
     Dblog  = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
     Logger = NLog.LogManager.GetCurrentClassLogger();
 }