Пример #1
0
    private static void InitializeLogging()
    {
        // Delete all log files older than 1 week
        try
        {
            var applicationDataDirectory = Catel.IO.Path.GetApplicationDataDirectory();
            if (Directory.Exists(applicationDataDirectory))
            {
                var logFiles = Directory.GetFiles(applicationDataDirectory, "*.log");
                foreach (var logFile in logFiles)
                {
                    var lastWriteTime = File.GetLastWriteTime(logFile);
                    if (lastWriteTime < DateTime.Now.AddDays(-7))
                    {
                        File.Delete(logFile);
                    }
                }
            }
        }
        catch (Exception)
        {
            // Ignore
        }

        var fileLogListener = LogHelper.CreateFileLogListener(AssemblyHelper.GetEntryAssembly().GetName().Name);

        fileLogListener.IgnoreCatelLogging = true;
        fileLogListener.IsDebugEnabled     = false;
        fileLogListener.IsInfoEnabled      = true;
        fileLogListener.IsWarningEnabled   = true;
        fileLogListener.IsErrorEnabled     = true;

        LogManager.AddListener(fileLogListener);
    }
Пример #2
0
        /// <summary>
        /// Handles the Startup event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.StartupEventArgs"/> instance containing the event data.</param>
        private void OnApplicationStartup(object sender, StartupEventArgs e)
        {
            Catel.Windows.StyleHelper.CreateStyleForwardersForDefaultStyles();

#if DEBUG
            var debugListener = new DebugLogListener();
            debugListener.IsDebugEnabled = false;

            LogManager.AddListener(debugListener);
#endif

            var serviceLocator = ServiceLocator.Default;

            var viewLocator = serviceLocator.ResolveType <IViewLocator>();
            viewLocator.NamingConventions.Add("[UP].Views.[VM]");
            viewLocator.NamingConventions.Add("[UP].Views.LogicInBehavior.[VM]");
            viewLocator.NamingConventions.Add("[UP].Views.LogicInBehavior.[VM]View");
            viewLocator.NamingConventions.Add("[UP].Views.LogicInBehavior.[VM]Window");
            viewLocator.NamingConventions.Add("[UP].Views.LogicInViewBase.[VM]");
            viewLocator.NamingConventions.Add("[UP].Views.LogicInViewBase.[VM]View");
            viewLocator.NamingConventions.Add("[UP].Views.LogicInViewBase.[VM]Window");

            var viewModelLocator = serviceLocator.ResolveType <IViewModelLocator>();
            viewModelLocator.NamingConventions.Add("Catel.Examples.AdvancedDemo.ViewModels.[VW]ViewModel");

            RootVisual = new MainPage();
        }
Пример #3
0
        public void Log_StatusNotEnabled()
        {
            var listener = new TestLogListener();

            listener.IsStatusEnabled = false;

            LogManager.AddListener(listener);

            TestLogListener.Log.Debug("debug");
            Assert.AreEqual(1, listener.DebugCount);

            TestLogListener.Log.Info("info");
            Assert.AreEqual(1, listener.InfoCount);

            TestLogListener.Log.Warning("warning");
            Assert.AreEqual(1, listener.WarningCount);

            TestLogListener.Log.Error("error");
            Assert.AreEqual(1, listener.ErrorCount);

            TestLogListener.Log.Status("status");
            Assert.AreEqual(0, listener.StatusCount);

            LogManager.RemoveListener(listener);
        }
Пример #4
0
 static CatelSample()
 {
     LogManager.AddListener(new LogListener
     {
         Action = (s, @event) => { LastMessage = s; }
     });
 }
Пример #5
0
        public void Log_DefaultIsEnabledValues()
        {
            var listener = new TestLogListener();

            Assert.IsTrue(listener.IsDebugEnabled);
            Assert.IsTrue(listener.IsInfoEnabled);
            Assert.IsTrue(listener.IsWarningEnabled);
            Assert.IsTrue(listener.IsErrorEnabled);
            Assert.IsTrue(listener.IsStatusEnabled);

            LogManager.AddListener(listener);

            TestLogListener.Log.Debug("debug");
            Assert.AreEqual(1, listener.DebugCount);

            TestLogListener.Log.Info("info");
            Assert.AreEqual(1, listener.InfoCount);

            TestLogListener.Log.Warning("warning");
            Assert.AreEqual(1, listener.WarningCount);

            TestLogListener.Log.Error("error");
            Assert.AreEqual(1, listener.ErrorCount);

            TestLogListener.Log.Status("status");
            Assert.AreEqual(1, listener.StatusCount);

            LogManager.RemoveListener(listener);
        }
Пример #6
0
        private static void test2()
        {
            var    commonMsgFormater = new CommonMsgFormater();
            Logger logger            = LogManager.CreatLogger();

            LogManager.AddListener(new ConsoleOutput(commonMsgFormater));
            LogManager.AddListener(new FileOutput(@"D:/MyLog.txt", commonMsgFormater));
            LogManager.AddEnableCategory("All");
            LogManager.Start();
            logger.Level = LogLevel.Warn;

            logger.Info("信息");
            logger.Debug("调试");
            logger.Warn("警告");
            logger.Error("错误");
            logger.Fatal("致命错误");

            List <Logger> loggers = new List <Logger>();

            for (int i = 0; i < 10; i++)
            {
                loggers.Add(LogManager.CreatLogger());
            }

            for (int i = 0; i < 10000; i++)
            {
                foreach (Logger logger1 in loggers)
                {
                    logger1.Warn(i.ToString());
                }
            }
        }
        private void SubscribeLogListener()
        {
            if (!_isViewModelActive)
            {
                return;
            }

            var logListenerType = LogListenerType;

            if (logListenerType == null)
            {
                return;
            }

            if (logListenerType == typeof(LogViewerLogListener))
            {
                _logListener = _logViewerLogListener;

                AddLogEntries(_logViewerLogListener.GetLogEntries(), true);
            }
            else
            {
                _logListener = _typeFactory.CreateInstance(logListenerType) as ILogListener;
                if (_logListener != null)
                {
                    LogManager.AddListener(_logListener);
                }
            }

            if (_logListener != null)
            {
                _logListener.IgnoreCatelLogging = IgnoreCatelLogging;
                _logListener.LogMessage        += OnLogMessage;
            }
        }
Пример #8
0
 public static void Init()
 {
     LogManager.AddListener(new LogListener
     {
         Action = (s, @event) => { LastMessage = s; }
     });
 }
Пример #9
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Application.Startup"/> event.
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs"/> that contains the event data.</param>
        protected override void OnStartup(StartupEventArgs e)
        {
#if DEBUG
            Catel.Logging.LogManager.AddDebugListener(true);

            var logPath = Path.Combine(GetType().Assembly.GetDirectory(), "debug.log");
            LogManager.AddListener(new FileLogListener(logPath, 25 * 1024));
#endif

            var languageService = ServiceLocator.Default.ResolveType <ILanguageService>();

            // Note: it's best to use .CurrentUICulture in actual apps since it will use the preferred language
            // of the user. But in order to demo multilingual features for devs (who mostly have en-US as .CurrentUICulture),
            // we use .CurrentCulture for the sake of the demo
            languageService.PreferredCulture = CultureInfo.CurrentCulture;
            languageService.FallbackCulture  = new CultureInfo("en-US");

            //var consoleLogListener = new ConsoleLogListener();
            //consoleLogListener.IgnoreCatelLogging = true;
            //LogManager.AddListener(consoleLogListener);

            Console.WriteLine(typeof(ILicenseService));

            StyleHelper.CreateStyleForwardersForDefaultStyles();

            base.OnStartup(e);
        }
Пример #10
0
        private static int Main(string[] args)
        {
#if DEBUG
            LogManager.AddDebugListener(true);
#endif

            var consoleLogListener = new ConsoleLogListener();
            LogManager.AddListener(consoleLogListener);

            var exitCode = 0;

            try
            {
                Log.Info("Example console app");
            }
            catch (Exception ex)
            {
                Log.Error(ex, "An unknown exception occurred");
                exitCode = -1;
            }

#if DEBUG
            if (Debugger.IsAttached)
            {
                WaitForKeyPress();
            }
#endif

            return(exitCode);
        }
        /// <summary>
        /// Configures the <see cref="IServiceLocator"/>. May be overwritten in a derived class to add specific
        /// type mappings required by the application.
        /// </summary>
        protected override void ConfigureContainer()
        {
            base.ConfigureContainer();
            Container.RegisterTypeIfNotYetRegistered <IModuleTracker, ModuleTracker>();

            LogManager.AddListener(_callbackLogger);
            Container.RegisterInstance <CallbackLogger>(_callbackLogger);
        }
Пример #12
0
        private static int Main(string[] args)
        {
#if DEBUG
            LogManager.AddDebugListener(true);
#endif

            var consoleLogListener = new OutputLogListener();
            LogManager.AddListener(consoleLogListener);

            Uri        remoteGitUrl = null;
            string     commitId     = null;
            string     baseDir      = null;
            string     pdbPath      = null;
            bool       skipVerify   = false;
            LinkMethod method       = LinkMethod.Http;
            var        arguments    = ArgumentSyntax.Parse(args, syntax =>
            {
                syntax.DefineOption("m|method", ref method, v => (LinkMethod)Enum.Parse(typeof(LinkMethod), v, true), "The method for SRCSRV to retrieve source code. One of <" + string.Join("|", Enum.GetNames(typeof(LinkMethod))) + ">. Default is " + method + ".");
                syntax.DefineOption("u|url", ref remoteGitUrl, s => new Uri(s, UriKind.Absolute), "Url to remote git repository.");
                syntax.DefineOption("commit", ref commitId, "The git ref to assume all the source code belongs to.");
                syntax.DefineOption("baseDir", ref baseDir, "The path to the root of the git repo.");
                syntax.DefineOption("s|skipVerify", ref skipVerify, "Verify all source files are available in source control.");
                syntax.DefineParameter("pdb", ref pdbPath, "The PDB to add source indexing to.");

                if (!string.IsNullOrEmpty(pdbPath) && !File.Exists(pdbPath))
                {
                    syntax.ReportError($"File not found: \"{pdbPath}\"");
                }

                if (!string.IsNullOrEmpty(baseDir) && !Directory.Exists(baseDir))
                {
                    syntax.ReportError($"Directory not found: \"{baseDir}\"");
                }
            });

            if (string.IsNullOrEmpty(pdbPath))
            {
                Log.Info(arguments.GetHelpText());
                return(1);
            }

            var options = new LinkOptions
            {
                GitRemoteUrl        = remoteGitUrl,
                GitWorkingDirectory = baseDir != null?Catel.IO.Path.GetFullPath(baseDir, Environment.CurrentDirectory) : null,
                                          CommitId   = commitId,
                                          SkipVerify = skipVerify,
                                          Method     = method,
            };

            if (!Linker.Link(pdbPath, options))
            {
                return(1);
            }

            WaitForKeyPressWhenDebugging();
            return(0);
        }
Пример #13
0
        /// <summary>
        /// Initializes the module.
        /// </summary>
        public static void Initialize()
        {
#if NET
            try
            {
                bool isWebContext = false;

                var httpContextType = TypeCache.GetTypeWithoutAssembly("System.Web.HttpContext");
                if (httpContextType != null)
                {
                    var currentPropertyInfo = httpContextType.GetProperty("Current", BindingFlags.Public | BindingFlags.Static);
                    if (currentPropertyInfo != null)
                    {
                        isWebContext = (currentPropertyInfo.GetValue(null, null) != null);
                    }
                }

                Configuration config = null;
                if (isWebContext)
                {
                    Log.Debug("Application is living in a web context, loading web configuration");

                    // All via reflection because we are support .NET 4.0 client profile, reflection equals this call:
                    //   config = Configuration.WebConfigurationManager.OpenWebConfiguration("~");
                    var webConfigurationManagerType    = TypeCache.GetTypeWithoutAssembly("System.Web.Configuration.WebConfigurationManager");
                    var openWebConfigurationMethodInfo = webConfigurationManagerType.GetMethodEx("OpenWebConfiguration", new [] { typeof(string) }, allowStaticMembers: true);
                    config = (Configuration)openWebConfigurationMethodInfo.Invoke(null, new [] { "~" });
                }
                else
                {
                    Log.Debug("Application is living in an application context, loading application configuration");

                    config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                }

                if (config != null)
                {
                    var configurationSection = config.GetSection <LoggingConfigurationSection>("logging", "catel");
                    if (configurationSection != null)
                    {
                        var logListeners = configurationSection.GetLogListeners();
                        foreach (var logListener in logListeners)
                        {
                            LogManager.AddListener(logListener);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to load log listeners from the configuration file");
            }
#endif

            var serviceLocator = ServiceLocator.Default;
            var module         = new CoreModule();
            module.Initialize(serviceLocator);
        }
Пример #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LoggerFacadeAdapter"/> class.
 /// </summary>
 /// <param name="log">
 /// The log.
 /// </param>
 /// <param name="relayCatelMessageToLoggerFacade">
 /// Option to relay catel message to logger facade
 /// </param>
 /// <exception cref="System.ArgumentNullException">
 /// The <paramref name="log"/> is <c>null</c>.
 /// </exception>
 public LoggerFacadeAdapter(ILog log, bool relayCatelMessageToLoggerFacade = false)
 {
     Argument.IsNotNull("log", log);
     _log = log;
     if (relayCatelMessageToLoggerFacade)
     {
         LogManager.AddListener(this);
     }
 }
Пример #15
0
        private static void AddFileLogListener(string prefix)
        {
            var fileLogListener = CreateFileLogListener(prefix);

            LogManager.AddListener(fileLogListener);

            Log.LogProductInfo();
            Log.LogDeviceInfo();
        }
Пример #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow"/> class.
        /// </summary>
        public MainWindow()
            : base(DataWindowMode.Custom)
        {
            InitializeComponent();

            LogManager.AddListener(new TextBoxLogListener(outputTextBox));

            Log.Info("Welcome to the example of Orc.Analytics. Use any of the buttons above to control the analytics. Log messages will appear here");
        }
Пример #17
0
        public void IsListenerRegistered_RegisteredListener()
        {
            LogManager.ClearListeners();

            var listener = new DebugLogListener();

            LogManager.AddListener(listener);
            Assert.IsTrue(LogManager.IsListenerRegistered(listener));
        }
Пример #18
0
 public CatelLoggerService(bool enableConsoleListener)
 {
     if (enableConsoleListener)
     {
         var logListener = new ConsoleLogListener {
             IgnoreCatelLogging = true
         };
         LogManager.AddListener(logListener);
     }
 }
Пример #19
0
        public void AddListener_UnregisteredListener()
        {
            LogManager.ClearListeners();

            var listener = new DebugLogListener();

            LogManager.AddListener(listener);
            Assert.IsTrue(LogManager.IsListenerRegistered(listener));
            Assert.AreEqual(1, LogManager.GetListeners().Count());
        }
Пример #20
0
        public StatusService(IStatusFilterService statusFilterService)
        {
            Argument.IsNotNull(() => statusFilterService);

            _statusFilterService = statusFilterService;

            var statusLogListener = new Orchestra.Logging.StatusLogListener(this);

            LogManager.AddListener(statusLogListener);
        }
Пример #21
0
        public MainWindow()
        {
            InitializeComponent();

            var logListener = new TextBoxLogListener(logTextBox);

            logListener.IgnoreCatelLogging = true;

            LogManager.AddListener(logListener);
        }
Пример #22
0
        private static int Main(string[] args)
        {
#if DEBUG
            LogManager.AddDebugListener(true);
#endif

            var consoleLogListener = new OutputLogListener();
            LogManager.AddListener(consoleLogListener);

            try
            {
                HelpWriter.WriteAppHeader(s => Log.Write(LogEvent.Info, s));

                Log.Info("Arguments: {0}", string.Join(" ", args));
                Log.Info(string.Empty);

                var context = ArgumentParser.ParseArguments(args);
                if (context.IsHelp)
                {
                    HelpWriter.WriteHelp(s => Log.Write(LogEvent.Info, s));

                    WaitForKeyPress();

                    return(0);
                }

                var parameters  = new List <IParameter>();
                var typeFactory = TypeFactory.Default;
                var initTypes   = TypeCache.GetTypes(x => typeof(RuleBase).IsAssignableFromEx(x) && !x.IsAbstract);
                foreach (var initType in initTypes)
                {
                    var initializer = (RuleBase)typeFactory.CreateInstance(initType);
                    parameters.Add(initializer.GetParameter(context));
                }

                foreach (var buildServer in BuildServerList.GetApplicableBuildServers(context))
                {
                    buildServer.WriteIntegration(parameters, x => Log.Info(x));
                }

#if DEBUG
                if (Debugger.IsAttached)
                {
                    WaitForKeyPress();
                }
#endif

                return(0);
            }
            catch (Exception)
            {
                return(-1);
            }
        }
Пример #23
0
        public MainView()
        {
            InitializeComponent();

            var logListener = new TextBoxLogListener(loggingTextBox)
            {
                IgnoreCatelLogging = true
            };

            LogManager.AddListener(logListener);
        }
Пример #24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RollingInMemoryLogService"/> class.
        /// </summary>
        /// <param name="logListener">The log listener. If <c>null</c>, this service will create its own log listener.</param>
        public RollingInMemoryLogService(RollingInMemoryLogListener logListener)
        {
            if (logListener == null)
            {
                logListener = new RollingInMemoryLogListener();
                LogManager.AddListener(logListener);
            }

            _rollingInMemoryLogListener             = logListener;
            _rollingInMemoryLogListener.LogMessage += OnLogListenerLogMessage;
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            LogManager.AddListener(new LogCatListener());
            LogManager.AddListener(new ToastListener(this));

            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
Пример #26
0
        public void ClearListeners()
        {
            var listener = new DebugLogListener();

            LogManager.AddListener(listener);

            Assert.AreNotEqual(0, LogManager.GetListeners().Count());

            LogManager.ClearListeners();

            Assert.AreEqual(0, LogManager.GetListeners().Count());
        }
Пример #27
0
    /// <summary>
    /// Initializes the module.
    /// </summary>
    public static void Initialize()
    {
        var serviceLocator = ServiceLocator.Default;

        var logListener = (from x in LogManager.GetListeners()
                           where x is LogViewerLogListener
                           select(LogViewerLogListener) x).FirstOrDefault();

        if (logListener == null)
        {
            logListener = new LogViewerLogListener
            {
                IgnoreCatelLogging = true,
                IsDebugEnabled     = true,
                IsInfoEnabled      = true,
                IsWarningEnabled   = true,
                IsErrorEnabled     = true
            };

            LogManager.AddListener(logListener);
        }

        serviceLocator.RegisterInstance <LogViewerLogListener>(logListener);

        serviceLocator.RegisterType <IAccentColorService, AccentColorService>();
        serviceLocator.RegisterType <IApplicationLogFilterGroupService, ApplicationLogFilterGroupService>();

        serviceLocator.RegisterType <ISuggestionListService, SuggestionListService>();
        serviceLocator.RegisterType <IValidationNamesService, ValidationNamesService>();
        serviceLocator.RegisterTypeIfNotYetRegistered <IConnectionStringBuilderServiceInitializer, ConnectionStringBuilderServiceInitializer>();
        serviceLocator.RegisterType <IConnectionStringBuilderService, ConnectionStringBuilderService>();
        serviceLocator.RegisterTypeIfNotYetRegistered <IControlToolManagerFactory, ControlToolManagerFactory>();

        // Override Catel.SelectDirectoryService with Orchestra.Services.SelectDirectoryService
        serviceLocator.RegisterType <ISelectDirectoryService, MicrosoftApiSelectDirectoryService>();

        serviceLocator.RegisterType <ITimeAdjustmentProvider, TimeAdjustmentProvider>();

        var viewModelLocator = serviceLocator.ResolveType <IViewModelLocator>();

        viewModelLocator.Register(typeof(CulturePicker), typeof(CulturePickerViewModel));
        viewModelLocator.Register(typeof(ValidationContextTree), typeof(ValidationContextTreeViewModel));
        viewModelLocator.Register(typeof(ValidationContextView), typeof(ValidationContextViewModel));
        viewModelLocator.Register(typeof(ConnectionStringBuilder), typeof(ConnectionStringBuilderViewModel));
        viewModelLocator.Register(typeof(ConnectionStringEditWindow), typeof(ConnectionStringEditViewModel));
        viewModelLocator.Register(typeof(ConnectionStringAdvancedOptionsWindow), typeof(ConnectionStringAdvancedOptionsViewModel));
        viewModelLocator.Register(typeof(DbConnectionProviderListWindow), typeof(DbConnectionProviderListViewModel));

        var languageService = serviceLocator.ResolveType <ILanguageService>();

        languageService.RegisterLanguageSource(new LanguageResourceSource("Orc.Controls", "Orc.Controls.Properties", "Resources"));
    }
Пример #28
0
    static CatelTests()
    {
        var moduleWeaver = new ModuleWeaver();

        assembly = moduleWeaver.ExecuteTestRun(
            assemblyPath: "AssemblyToProcess.dll",
            ignoreCodes: new[] { "0x80131869" }).Assembly;

        LogManager.AddListener(new LogListener
        {
            Action = LogMessage
        });
    }
Пример #29
0
        public CustomStatusService(IStatusFilterService statusFilterService, IDispatcherService dispatcherService) :
            base(statusFilterService)
        {
            Argument.IsNotNull(() => statusFilterService);
            Argument.IsNotNull(() => dispatcherService);

            _statusFilterService = statusFilterService;
            _dispatcherService   = dispatcherService;

            var statusLogListener = new StatusLogListener(this);

            LogManager.AddListener(statusLogListener);
        }
Пример #30
0
    private static void InitializeLogging()
    {
        LogHelper.CleanUpAllLogTypeFiles();

        var fileLogListener = LogHelper.CreateFileLogListener(LogFilePrefixes.EntryAssemblyName);

        fileLogListener.IsDebugEnabled   = false;
        fileLogListener.IsInfoEnabled    = true;
        fileLogListener.IsWarningEnabled = true;
        fileLogListener.IsErrorEnabled   = true;

        LogManager.AddListener(fileLogListener);
    }