コード例 #1
0
        public void WriteLog(int tipo, Object mensaje)
        {
            log4net.GlobalContext.Properties["mensaje"] = "Exepcion Mensaje";
            try
            {
                if (tipo == 0)
                {
                    log.Debug(mensaje);
                }
                if (tipo == 1)
                {
                    log.Warn(mensaje);
                }
                if (tipo == 2)
                {
                    log.Error(mensaje);
                }

                if (tipo == 3)
                {
                    log.Fatal(mensaje);
                }
            }
            catch (Exception ex) {
                throw ex;
            }
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: SwatInc/CD4
        static void Main()
        {
            try
            {
                _log.Info("Initialize dependency injection system.");
                var container = ContainerConfig.Configure();

                using var scope = container.BeginLifetimeScope();
                var app = scope.Resolve <ICd4Application>();
                FormFactory.Use(container.Resolve <IFormFactory>());

                app.Run();
            }
            catch (Exception ex)
            {
                _log.Fatal(ex.Message + "\n", ex);

                //handle any inner exceptions
                var inner = ex.InnerException;

                while (inner != null)
                {
                    _log.Fatal($"Inner Stack Trace\n{inner.Message}\n{inner.StackTrace}");
                    //get the next inner exception for next iteration
                    inner = inner.InnerException;
                }
            }
        }
コード例 #3
0
        public static void StartServer()
        {
            try
            {
                log4net.Config.XmlConfigurator.Configure();

                log.Info("Application is starting");

                // get this one from appsetting
                string[] prefixes = Utils.GetAppSetting("HOSTLIST").Split(',');


                server = new HttpServer(prefixes, "Navision");
                log.Debug("adresser:");

                foreach (var p in prefixes)
                {
                    log.Debug(p.ToString());
                }

                new Thread(server.Start).Start();
            }
            catch (Exception e)
            {
                log.Fatal("Exception in Main", e);
                log.Fatal(e.Message);
            }
        }
コード例 #4
0
        //Primer método que se ejecuta cuando corre el servicio (onStart)
        public void IniciarMigracion(Object state)
        {
            try
            {
                string stringConexion = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
                NegociosSisPackFactory.SisPackFactory.setStringConexion(stringConexion);
                NegociosSisPackFactory.SisPackFactory.Inicializar();

                int nroIntentos = System.Configuration.ConfigurationSettings.AppSettings["IntentosMigracionDiaria"] == null ? 4 : Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["IntentosMigracionDiaria"]);

                if (nroIntentos > 0)
                {
                    MigrarServiciosDiario(nroIntentos, (int)SisPack.Implementaciones.Andesmar);
                }
                else //Si en el app.config se guardar 0 o un nro negativo, debe intentarlo por lo menos una vez
                {
                    MigrarServiciosDiario(1, (int)SisPack.Implementaciones.Andesmar);
                }

                //Logger.Info("El servicio de migración finalizó con éxito.");
            }
            catch (Exception ex)
            {
                Logger.Fatal("Ocurrio un error fatal en el método IniciarMigracion(Object state).", ex);
            }
        }
コード例 #5
0
        public void Log(string level, string message)
        {
            try
            {
                switch (level)
                {
                case "Info":
                    logger.Info(message);
                    break;

                case "Warn":
                    logger.Warn(message);
                    break;

                case "Error":
                    logger.Error(message);
                    break;

                case "Fatal":
                    logger.Fatal(message);
                    break;

                case "Debug":
                    logger.Debug(message);
                    break;

                default:
                    logger.Info(message);
                    break;
                }
            }
            catch {
                throw new NotImplementedException();
            }
        }
コード例 #6
0
        void StartCleanUp(string folder, int folderIndex)
        {
            SummonDirectoryLineman(folder);
            log.Info("Построено виртуальное дерево файлов для сравнения. В дереве элементов: " + cleanupFileList.Count);
            DateTime deletedUponTime = DateTime.Now;

            foreach (FileInfo deletionCandidate in cleanupFileList.OrderBy(d => d.LastWriteTime))
            {
                deletedUponTime = deletionCandidate.LastWriteTime;
                if (CheckExitConditions(folderIndex))
                {
                    log.Info("Состояние нехватки места на диске успешно устранено! Папка " + folder + " очищена аж по " + deletedUponTime);
                    return;
                }
                else
                {
                    try
                    {
                        deletionCandidate.Delete();
                    }
                    catch (Exception e)
                    {
                        log.Error("Не удалось удалить файл " + deletionCandidate.FullName + " по причине отказа в доступе либо иным причинам, перечисленным ниже:\r\n" + e.Message);
                        //throw;
                    }
                }
            }
            log.Fatal("Не удалось восстановить свободное место на диске! В Папке " + folder + " слишком мало доступных для удаления файлов!");
        }
コード例 #7
0
 /// <summary>
 /// Test reference creation through unmanaged code.
 /// </summary>
 /// <returns>Reference result.</returns>
 public static int ReferenceTest()
 {
     try
     {
         // Attempt to create a reference through unmanaged code (C++ DLL).
         int result = CreateReference();
         // If no exception occurred, output successful result.
         Logging.Info($"Reference successfully created at: {result}.");
         // Return result.
         return(result);
     }
     catch (System.AccessViolationException exception)
     {
         // Output explicit exception.
         Logging.Fatal(exception);
     }
     catch (BadImageFormatException exception)
     {
         Logging.Fatal(exception);
     }
     catch (Exception exception)
     {
         // Output inexplicit exception.
         Logging.Fatal(exception);
     }
     // Return zero to indicate failure.
     return(0);
 }
コード例 #8
0
 public void Fatal(object message)
 {
     if (IsFatalEnabled)
     {
         log.Fatal(message);
     }
 }
コード例 #9
0
        public SalesManagerService()
        {
            InitializeComponent();

            log4net.Config.XmlConfigurator.Configure();
            _logger = LogManager.GetLogger("Windows Service");

            ApplicationConfigValidator validator = new ApplicationConfigValidator();
            try
            {
                validator.Validate();

                _serverFolderPath = ConfigurationManager.AppSettings["ServerFolder"];
                _wrongFilesFolderPath = ConfigurationManager.AppSettings["NotAppropriateFilesFolder"];
                _processedFiles = ConfigurationManager.AppSettings["ProcessedFilesFolder"];

                _cancelationTokenSource = new CancellationTokenSource();

                var taskScheduler =
                    new LimitedTaskScheduler(Int32.Parse(ConfigurationManager.AppSettings["MaxDatabaseConnections"]));
                _taskFactory = new TaskFactory(taskScheduler);
                _fileHandler = new FileHandler();
            }
            catch (ConfigurationErrorsException ex)
            {
                _logger.Fatal("Eroor occurs with configuration. " + ex.Message);
                return;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                _logger.Fatal("Erorr occurs with max number of connections to database. " + ex.Message);
                return;
            }
        }
コード例 #10
0
ファイル: Log4NetLogger.cs プロジェクト: songtaojie/Common
 public void Fatal(string message)
 {
     if (log.IsFatalEnabled)
     {
         log.Fatal(message);
     }
 }
コード例 #11
0
        //--- Class Methods ---
        public static bool Convert(string confluenceXMLRPCUrl, string confluenceAPIUrl, string confluenceUserName, string confluenceUserPassword, string dreamAPI,
                                   string dekiUserName, string dekiUserPassword, bool compatibleConvertUserPermissions,
                                   List <string> spacesToConvert, bool processNewsPages, bool processPersonalSpaces, string fallbackSpacePrefix)
        {
            using (ACConverter converter = new ACConverter()) {
                try {
                    Log.Info("Connecting to MindTouch API");
                    converter.ConnectToDeki(dreamAPI, dekiUserName, dekiUserPassword);
                } catch (DreamResponseException dre) {
                    Log.Fatal("Can not connect to MindTouch API server.", dre);
                    return(false);
                }

                if (converter._connectedToDeki)
                {
                    Log.Info("Successfully connected to MindTouch");
                }
                else
                {
                    Log.Fatal("Can not connect to MindTouch server.");
                    return(false);
                }

                try {
                    Log.Info("Connecting to Confluence API");
                    converter.ConnectToConfluence(confluenceAPIUrl, confluenceUserName, confluenceUserPassword);
                } catch (System.Net.WebException e) {
                    Log.ErrorExceptionFormat(e, "Can not connect to Confluence");
                    return(false);
                } catch (System.Web.Services.Protocols.SoapException e) {
                    if ((e.Detail != null) && (e.Detail.OuterXml != null))
                    {
                        Log.Fatal("Can not connect to Confluence: " + e.Detail.OuterXml, e);
                    }
                    else
                    {
                        Log.Fatal("Can not connect to Confluence", e);
                    }
                    return(false);
                }

                // The base URL needs to be set globally in a static variable so that macros can access it.
                // For example so the "include" macro knows if a given link is for a page on the current confluence site or not.
                ConfluenceBaseURL = converter._confluenceService.GetServerInfo().baseUrl;

                Log.Info("Connecting to Confluence XMLRPC API");
                if (!converter.ConnectToConfluenceRPC(confluenceXMLRPCUrl, confluenceUserName, confluenceUserPassword))
                {
                    Log.Fatal("Can not connect to Confluence XML RPC server.");
                }

                Log.Info("Successfully connected to Confluence");
                RemoteServerInfo confluenceServerInfo = converter._confluenceService.GetServerInfo();
                Log.InfoFormat("Confluence version: {0}.{1}.{2}", confluenceServerInfo.majorVersion.ToString(),
                               confluenceServerInfo.minorVersion.ToString(), confluenceServerInfo.patchLevel.ToString());

                converter.Convert(new XUri(confluenceServerInfo.baseUrl), compatibleConvertUserPermissions, processNewsPages, spacesToConvert, processPersonalSpaces, fallbackSpacePrefix);
                return(true);
            }
        }
コード例 #12
0
ファイル: Form1.cs プロジェクト: TerminusMKB/AccessController
        private void Form1_Load(object sender, EventArgs e)
        {
            Program.form1    = (Form1)sender;
            Program.listener = new HttpListener();
            Program.listener.Prefixes.Add("http://*:27099/");
            try
            {
                Program.listener.Start();
            }
            catch (HttpListenerException ex)
            {
                Program.form1.labelListening.Text      = ex.Message;
                Program.form1.labelListening.ForeColor = System.Drawing.Color.Red;
                log.Fatal("Listener не смог стартовать: " + ex.Message);
                return;
            }
            if (Program.listener == null || !Program.listener.IsListening)
            {
                Program.form1.labelListening.Text      = "Не удалось открыть порт";
                Program.form1.labelListening.ForeColor = System.Drawing.Color.Red;
                log.Fatal("Listener не смог стартовать");
                return;
            }

            var listenerThread = new Thread(listenerThreadWatcher);

            listenerThread.IsBackground = true;
            listenerThread.Start();
            //Program.ZApi.addKey(31351, -1, "213,15275");
            //Program.ZApi.deleteKey(31351, 455);
            //Program.ZApi.deleteKey(31351, 433);
            //Program.ZApi.getKeys(31351, 1, 2);
        }
コード例 #13
0
 /// <summary>
 /// 发布致命性错误
 /// </summary>
 /// <param name="message"></param>
 /// <param name="exception"></param>
 public void Fatal(object message, Exception exception)
 {
     if (log.IsFatalEnabled)
     {
         log.Fatal(message, exception);
     }
 }
コード例 #14
0
        protected override void OnStart(string[] args)
        {
            //System.IO.File.Create("test.txt");
            log.Info("Service started");

            /*try
             * {
             *  FSWatcher.Path = watchPath;
             * }
             * catch (Exception ex)
             * {
             *  log.Fatal(ex.ToString());
             * }*/

            try
            {
                timer.Elapsed += new ElapsedEventHandler(FSWatcher_Tick);

                timer.Interval = GetInterval();

                timer.Enabled = true;
            }
            catch (Exception ex)
            {
                log.Fatal(ex.ToString());
                throw ex;
            }
        }
コード例 #15
0
        public  void AddFatalLog(ILog logger,Exception errormessage)
        {

            if (!string.IsNullOrEmpty(Data))
            {
                object[] args = new object[4];
                args[0] = LogProcess;
                args[1] = User;
                args[2] = Data;
                args[3] = Message;
                string ermes = string.Format("[{0}] [{1}] [{2}] [{3}]", args);
                logger.Fatal(ermes, errormessage);
            }
            else
            {
                object[] args = new object[4];
                args[0] = LogProcess;
                args[1] = User;
                args[2] = Message;
                string ermes = string.Format("[{0}] [{1}] [{2}] ", args);
                logger.Fatal(ermes, errormessage);
                    
            }



        }
コード例 #16
0
        void ILog.Log(LogLevel level, Exception exception, object message)
        {
            switch (level)
            {
            case LogLevel.Debug:
                _inner.Debug(message, exception);
                break;

            case LogLevel.Info:
                _inner.Info(message, exception);
                break;

            case LogLevel.Warn:
                _inner.Warn(message, exception);
                break;

            case LogLevel.Error:
                _inner.Error(message, exception);
                break;

            case LogLevel.Fatal:
                _inner.Fatal(message, exception);
                break;

            default:
                throw new ArgumentOutOfRangeException("level");
            }
        }
コード例 #17
0
 /// <summary>
 /// 致命错误
 /// </summary>
 /// <param name="Message"></param>
 public static void FataInfo(string Message)
 {
     if (!log.IsFatalEnabled)
     {
         SetConfig();
     }
     log.Fatal(Message);
 }
コード例 #18
0
 public void Fatal(string message, params object[] args)
 {
     if (!String.IsNullOrWhiteSpace(message))
     {
         var messageToTrace = string.Format(CultureInfo.InvariantCulture, message, args);
         SettingProperties();
         _log.Fatal(TraceMessage(messageToTrace));
     }
 }
コード例 #19
0
        public AgentService()
        {
            logger = LogManager.GetLogger("AgentService");
            logger.Info("AgentService initializing...");

            // TODO: Extract class ConfigurationManager
            // Read controller address
            if (ConfigurationManager.AppSettings["ControllerAddress"] == null)
            {
                logger.Fatal("ControllerAddress setting not found in App.config file!");
                throw new Exception("ControllerAddress setting not found in App.config file!");
            }

            var controllerAddress = ConfigurationManager.AppSettings["ControllerAddress"];

            // Read controller port
            if (ConfigurationManager.AppSettings["ControllerPort"] == null)
            {
                logger.Fatal("ControllerPort setting not found in App.config file!");
                throw new Exception("ControllerPort setting not found in App.config file!");
            }

            int controllerPort;
            if (!int.TryParse(ConfigurationManager.AppSettings["ControllerPort"], out controllerPort))
            {
                logger.Fatal("ControllerPort setting is not an integer!");
                throw new Exception("ControllerPort setting is not an integer!");
            }

            // Read threads count value
            int threadsCount;
            if (ConfigurationManager.AppSettings["ThreadsCount"] != null)
            {
                if (!int.TryParse(ConfigurationManager.AppSettings["ThreadsCount"], out threadsCount))
                {
                    threadsCount = DefaultThreadsCount;
                }
            }
            else
            {
                threadsCount = DefaultThreadsCount;
            }

            // Create clients
            this.clients = new List<AgentClient>();
            for (var i = 1; i <= threadsCount; i++)
            {
                var client = new AgentClient(controllerAddress, controllerPort, logger);
                this.clients.Add(client);
            }

            logger.Info("AgentService initialized.");
        }
コード例 #20
0
        /// <inheritdoc />
        /// <overloads>
        /// <inheritdoc />
        /// </overloads>
                #pragma warning restore 1573
        public override void Write
        (
            LogLevel logLevel,
            string message,
            [CallerMemberName]
            string callerMemberName = "",
            [CallerFilePath]
            string callerFilePath = "",
            [CallerLineNumber]
            int callerLineNumber = 0
        )
        {
            if (IgnoreLogLevel(logLevel))
            {
                return;
            }

            if (message == null)
            {
                return;
            }

            SetCallerContext(callerMemberName, callerFilePath, callerLineNumber.ToString());

            if (logLevel == LogLevel.Trace)
            {
                _log.Debug(message);
            }
            else if (logLevel == LogLevel.Debug)
            {
                _log.Debug(message);
            }
            else if (logLevel == LogLevel.Info)
            {
                _log.Info(message);
            }
            else if (logLevel == LogLevel.Warn)
            {
                _log.Warn(message);
            }
            else if (logLevel == LogLevel.Error)
            {
                _log.Error(message);
            }
            else if (logLevel == LogLevel.Fatal)
            {
                _log.Fatal(message);
            }

            SetCallerContext(null, null, null);
        }
コード例 #21
0
ファイル: Program.cs プロジェクト: susloparovdenis/nimator
        static void UnhandledExceptionLogger(object sender, UnhandledExceptionEventArgs eventArgs)
        {
            var exc = eventArgs.ExceptionObject as Exception;

            if (exc != null)
            {
                logger.Fatal("Unhandled exception occurred.", exc);
            }
            else
            {
                logger.Fatal("Fatal problem without Excption occurred.");
                logger.Fatal(eventArgs.ExceptionObject);
            }
        }
コード例 #22
0
 protected void Application_Error(object sender, EventArgs e)
 {
     _logger = ServiceLocator.Current.GetInstance<ILog>();
     _logger.Fatal("An unhandled exception occurred in ASP.NET processing: " + Server.GetLastError(), Server.GetLastError());
     //DataManager.Dispose();
     
 }
コード例 #23
0
 /// <summary>
 /// 记录严重错误
 /// </summary>
 /// <param name="info"></param>
 /// <param name="se"></param>
 public static void Fatal(string info, Exception se)
 {
     if (Instance.IsFatalEnabled)
     {
         Instance.Fatal(info, se);
     }
 }
コード例 #24
0
        public static void logData(string data, GameDataStorageLayerUtils.LogLevels level)
        {
            switch (level)
            {
            case GameDataStorageLayerUtils.LogLevels.Info:
                log.Info(data);
                break;

            case GameDataStorageLayerUtils.LogLevels.Debug:
                log.Debug(data);
                break;

            case GameDataStorageLayerUtils.LogLevels.Error:
                log.Error(data);
                break;

            case GameDataStorageLayerUtils.LogLevels.Fatal:
                log.Fatal(data);
                break;

            default:
                log.Info(data);
                break;
            }
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: hoxily/Wuziqi
 static void Main(string[] args)
 {
     Logger = LogManager.GetLogger("default");
     try
     {
         Logger.DebugFormat("Server powered up");
         Logger.DebugFormat("Loading configuration");
         ConfigManager.LoadConfigs();
         string addr = ConfigManager.GetConfig("GameServer.ListenAddress");
         string port = ConfigManager.GetConfig("GameServer.ListenPort");
         Logger.DebugFormat("Trying to listen at {0}:{1}", addr, port);
         TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Parse(addr), Convert.ToInt32(port)));
         listener.Start();
         while (true)
         {
             TcpClient client = listener.AcceptTcpClient();
             ClientServant servant = new ClientServant(client);
             Program.Logger.DebugFormat("New client connected from: {0}", servant.ClientIPEndPoint);
             servant.Start();
         }
     }
     catch (Exception e)
     {
         Logger.FatalFormat("Unhandled exception: {0}, stacktrace: {1}", e.Message, e.StackTrace);
         Logger.Fatal("Server shutdown");
     }
 }
コード例 #26
0
        static void Main(string[] args)
        {
            //log4net.Config.XmlConfigurator.Configure();

            //ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

            log.Debug("Hello World!");
            log.Info("I'm a simple log4net tutorial.");
            log.Warn("... better be careful ...");
            log.Error("ruh-roh: an error occurred");
            log.Fatal("OMG we're dooooooomed!");

            log.Debug(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

            //LogWritter.Debug("web I Debug");

            //LogWritter.Info("web I Info");

            //LogWritter.Error("web I Error");

            //Thread t = new Thread(WriteY);          // Kick off a new thread
            //t.Start();                               // running WriteY()

            //// Simultaneously, do something on the main thread.
            //for (int i = 0; i < 10; i++) log.Debug("x" + i);
        }
コード例 #27
0
        protected void Application_Start()
        {
            AppDomain.CurrentDomain.UnhandledException += Application_Error;
            try
            {
                XmlConfigurator.Configure();
                AppLogger = LogManager.GetLogger(GetType());
                AppLogger.Info("Application_Start...");

                AppLogger.Info("Bootstrapping the container...");
                Container = ContainerConfig.Config(AppLogger);

                AppLogger.Info("Setting the Controller Factory...");
                var controllerFactory = new WindsorControllerFactory(Container.Kernel);
                ControllerBuilder.Current.SetControllerFactory(controllerFactory);

                AreaRegistration.RegisterAllAreas();

                WebApiConfig.Register(GlobalConfiguration.Configuration);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                AuthConfig.RegisterAuth();
            }
            catch (Exception ex)
            {
                AppLogger.Fatal("Application_Start FAILED", ex);
                throw;
            }
        }
コード例 #28
0
 public static void Fatal()
 {
     if (Log.IsFatalEnabled)
     {
         Log.Fatal(_message);
     }
 }
コード例 #29
0
        private static void DoLog(string message, LogMessageType messageType)
        {
            Console.WriteLine(message);
            switch (messageType)
            {
            case LogMessageType.Debug:
                _log.Debug(message);
                break;

            case LogMessageType.Info:
                _log.Info(message);
                break;

            case LogMessageType.Warn:
                _log.Warn(message);
                break;

            case LogMessageType.Error:
                _log.Error(message);
                break;

            case LogMessageType.Fatal:
                _log.Fatal(message);
                break;
            }
        }
コード例 #30
0
ファイル: Logger.cs プロジェクト: yancyn/BumbleeBee
 public static void Fatal(System.Type type, object message)
 {
     logger = LogManager.GetLogger(type);
     if (!logger.Logger.Repository.Configured)
         XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(GetConfigFile() + ".config"));
     logger.Fatal(message);
 }
コード例 #31
0
        public static void LogEntrance(LogType type, int eventId, string module, string message, log4net.ILog logger)
        {
            switch (type)
            {
            case LogType.Default:
                logger.Info("发生模块:" + module + ",模块ID:" + eventId + "||" + message);
                break;

            case LogType.Error:
                logger.Error("发生模块:" + module + ",模块ID:" + eventId + "||" + message);
                break;

            case LogType.Info:
                logger.Info("发生模块:" + module + ",模块ID:" + eventId + "||" + message);
                break;

            case LogType.Fail:
                logger.Fatal("发生模块:" + module + ",模块ID:" + eventId + "||" + message);
                break;

            case LogType.Debug:
                logger.Debug("发生模块:" + module + ",模块ID:" + eventId + "||" + message);
                break;
            }
        }
コード例 #32
0
 /// <summary>
 /// Used for logging the exception message.
 /// </summary>
 /// <param name="s"></param>
 public static void Exception(object s)
 {
     if (FatalLog.IsFatalEnabled)
     {
         FatalLog.Fatal(s);
     }
 }
コード例 #33
0
ファイル: Logger.cs プロジェクト: qkxyk/hxcore
        /// <summary>
        /// 格式化输出异常信息
        /// </summary>
        /// <param name="level"></param>
        /// <param name="message"></param>
        /// <param name="exception"></param>
        private void Log(LoggerLevel level, string message, Exception exception)
        {
            switch (level)
            {
            case LoggerLevel.Debug:
                _Logger4net.Debug(message, exception);
                break;

            case LoggerLevel.Info:
                _Logger4net.Info(message, exception);
                break;

            case LoggerLevel.Warn:
                _Logger4net.Warn(message, exception);
                break;

            case LoggerLevel.Error:
                _Logger4net.Error(message, exception);
                break;

            case LoggerLevel.Fatal:
                _Logger4net.Fatal(message, exception);
                break;
            }
        }
コード例 #34
0
ファイル: Logger.cs プロジェクト: ArnePlanka/ReadsoftServer
        public static void Fatal(string message)
        {
            StackFrame sf     = new StackFrame(1);
            string     Method = sf.GetMethod().ToString();

            log.Fatal(Method + " " + message);
        }
コード例 #35
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("log4net!");


        //我们会以类(class)的类型(type)为参数来调用GetLogger(),
        //以便跟踪我们正在进行日志记录的类。传递的类(class)的类型(type)可以用typeof(Classname)方法来获得
        // log4net.ILog log = log4net.LogManager.GetLogger(typeof(log4Net));

        //也可以通过反射获得
        log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        log.Error("log4net error", new Exception("在这里发生了一个error异常!"));
        log.Fatal("log4net  fatal", new Exception("在发生了一个致命fatal错误"));
        log.Info("log4net info 提示:系统正在运行");
        log.Debug("log4net 调试信息:debug");
        log.Warn("log4net 警告:warn");

        int n = 0;

        for (n = 1; n <= 10; n++)
        {
            if (n % 2 == 0)
            {
                string s = n.ToString();
                log.Info(s + "为偶数");
            }
            else
            {
                string s = n.ToString();
                log.Warn(s + "为奇数");
            }
        }
    }
コード例 #36
0
        protected override void OnWrite(LogLevel level, string message)
        {
            switch (level)
            {
            case LogLevel.Debug:
                loger.Debug(message);
                break;

            case LogLevel.Warn:
                loger.Warn(message);
                break;

            case LogLevel.Error:
                loger.Error(message);
                break;

            case LogLevel.Info:
                loger.Info(message);
                break;

            case LogLevel.Fatal:
                loger.Fatal(message);
                break;
            }
        }
コード例 #37
0
ファイル: Log4NetObserver.cs プロジェクト: grouptheory/moadb
        /*
         * Removed this when we provided an overload for base.FormatMessage
         * that will return a message without any date time stamps
         * Josh & Mohamed
         * November 29, 2007
         */

        //private string RemovePrefixDate(string message)
        //{
        //    int amEndDateIndex = message.IndexOf("AM");
        //    int pmEndDateIndex = message.IndexOf("PM");

        //    amEndDateIndex += 2; pmEndDateIndex += 2;

        //    string amPrefix = message.Remove(amEndDateIndex);
        //    string pmPrefix = message.Remove(pmEndDateIndex);

        //    DateTime dateTime;
        //    if (DateTime.TryParse(amPrefix, out dateTime)) return message.Substring(amEndDateIndex);
        //    if (DateTime.TryParse(pmPrefix, out dateTime)) return message.Substring(pmEndDateIndex);

        //    return message;
        //}

        /// <summary>
        /// log message based on log level
        /// </summary>
        /// <param name="message"></param>
        /// <param name="e"></param>
        private void Log(string message, LogEventArgs e)
        {
            switch (e.LogLevel)
            {
            case LogLevel.Debug:
                _logger.Debug(message);
                break;

            case LogLevel.Error:
                _logger.Error(message);
                break;

            case LogLevel.Fatal:
                _logger.Fatal(message);
                break;

            case LogLevel.Info:
                _logger.Info(message);
                break;

            case LogLevel.Warning:
                _logger.Warn(message);
                break;

            default:
                throw new Exception("Unsupported log level.");
            }
        }
コード例 #38
0
        static void Main(string[] args)
        {
            ApplicationConfigValidator validator = new ApplicationConfigValidator();

            log4net.Config.XmlConfigurator.Configure();
            _logger = LogManager.GetLogger("Console application");

            try
            {
                validator.Validate();

                _serverFolderPath = ConfigurationManager.AppSettings["ServerFolder"];
                _wrongFilesFolderPath = ConfigurationManager.AppSettings["NotAppropriateFilesFolder"];
                _processedFiles = ConfigurationManager.AppSettings["ProcessedFilesFolder"];

                var taskScheduler =
                    new LimitedTaskScheduler(Int32.Parse(ConfigurationManager.AppSettings["MaxDatabaseConnections"]));
                _taskFactory = new TaskFactory(taskScheduler);
                _fileHandler = new FileHandler();
            }
            catch (ConfigurationErrorsException ex)
            {
                _logger.Fatal("Eroor occurs with configuration. " + ex.Message);
                return;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                _logger.Fatal("Erorr occurs with max number of connections to database. " + ex.Message);
                return;
            }

            ScanServerFolder();

            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = _serverFolderPath;
            watcher.Filter = "*.csv";
            watcher.Created += new FileSystemEventHandler(OnChanged);

            watcher.EnableRaisingEvents = true;

            Console.Read();
        }
コード例 #39
0
ファイル: LogHelper.cs プロジェクト: cnquan/tasker
 public static void Write(string msg, LogLevel lv = LogLevel.INFO)
 {
     log4net.GlobalContext.Properties["LogName"] = string.Format("{0}.{1}.log", DateTime.Now.ToString("yyyy-MM-dd"), lv.ToString().ToLower());
     _Log = LogManager.GetLogger(typeof(LogHelper));
     switch (lv)
     {
         case LogLevel.ALL: _Log.Info(msg); break;
         case LogLevel.DEBUG: _Log.Debug(msg); break;
         case LogLevel.ERROR: _Log.Error(msg); break;
         case LogLevel.FATAL: _Log.Fatal(msg); break;
         case LogLevel.INFO: _Log.Info(msg); break;
         case LogLevel.WARN: _Log.Warn(msg); break;
         default:
             _Log.Info(msg); break;
     }
 }
コード例 #40
0
ファイル: App.xaml.cs プロジェクト: ichengzi/atnets
        public App()
        {
            log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

            log.Info("程序启动");
            try
            {
                log.Info("启动初始化启动窗口");
                SplashScreen splashScreen = new SplashScreen("icons/SplashScreen.png");
                splashScreen.Show(true);
            }
            catch (Exception ex)
            {
                log.Fatal("初始化启动窗口出错", ex);
            }
        }
コード例 #41
0
        public static ExtensionPointsConfiguration ReadAndValidate(ILog logger)
        {
            Contract.Requires(logger != null, "ExtensionPointsConfigurationValidator:Validate - logger cannot be null!");

            logger.Info("Validating configuration started");
            ExtensionPointsConfiguration extensionPointsConfiguration = null;
            try
            {
                extensionPointsConfiguration = TryRetrieveConfigurationObject();
            }
            catch(Exception ex)
            {
                logger.Fatal("Validation failed: " + ex.Message);
                return null;
            }
            logger.Info("Validating configuration finished");
            return extensionPointsConfiguration;
        }
コード例 #42
0
        private void ExecuteScriptIfFoundInPackage(DeploymentContext context, string scriptPath, ILog logger)
        {
            var file = context.Package.GetFiles().SingleOrDefault(f => f.Path.Equals(scriptPath, StringComparison.InvariantCultureIgnoreCase));

            if (file == null)
            {
                return;
            }

            logger.DebugFormat("Found script {0}, executing...", scriptPath);

            try
            {
                LoadAndExecuteScript(context, Path.Combine(context.WorkingFolder, file.Path), logger);
            }
            catch (Exception ex)
            {
                logger.Fatal("Failed executing powershell script " + file.Path, ex);
            }
        }
コード例 #43
0
        protected override void OnStart(string[] args)
        {
            _log = LogManager.GetLogger(this.GetType());
            _isStopping = false;

            try
            {
                _log.Info("Starting minecraft");

                MinecraftConfig config = ConfigurationManager.GetSection(
                    typeof(MinecraftConfig).Name) as MinecraftConfig;

                Process startCmd = new Process();
                startCmd.StartInfo.FileName = config.JavaExecutable;
                startCmd.StartInfo.Arguments = string.Format("-Xmx{0}M -Xms{1}M -jar {2}\\minecraft_server.jar nogui",
                    config.MaxHeapInMegabytes, config.InitialHeapInMegabytes, config.MinecraftJarDirectory);
                startCmd.StartInfo.WorkingDirectory = config.MinecraftJarDirectory;
                startCmd.StartInfo.UseShellExecute = false;
                startCmd.StartInfo.RedirectStandardInput = true;
                startCmd.StartInfo.RedirectStandardOutput = true;
                startCmd.StartInfo.RedirectStandardError = true;
                startCmd.EnableRaisingEvents = true;

                startCmd.OutputDataReceived += new DataReceivedEventHandler(startCmd_OutputDataReceived);
                startCmd.ErrorDataReceived += new DataReceivedEventHandler(startCmd_ErrorDataReceived);
                startCmd.Exited += new EventHandler(startCmd_Exited);

                _log.InfoFormat("Executing '{0} {1}'", startCmd.StartInfo.FileName, startCmd.StartInfo.Arguments);

                startCmd.Start();

                startCmd.BeginOutputReadLine();
                startCmd.BeginErrorReadLine();

                _standardInput = startCmd.StandardInput;
            }
            catch (Exception ex)
            {
                _log.Fatal("Failed to start minecraft", ex);
            }
        }
コード例 #44
0
 private void Log(ILog log, Log4NetAttribute.Levels level, string strText)
 {
     switch(level)
     {
         case Log4NetAttribute.Levels.DEBUG:
             log.Debug(strText);
             break;
         case Log4NetAttribute.Levels.ERROR:
             log.Error(strText);
             break;
         case Log4NetAttribute.Levels.FATAL:
             log.Fatal(strText);
             break;
         case Log4NetAttribute.Levels.INFO:
             log.Info(strText);
             break;
         case Log4NetAttribute.Levels.WARN:
             log.Warn(strText);
             break;
     }
 }
コード例 #45
0
 public void Log(string message, LogLevel level, Type type)
 {
     _log = LogManager.GetLogger(type);
     switch (level)
     {
         case LogLevel.Info:
             _log.Info(message);
             break;
         case LogLevel.Debug:
             _log.Debug(message);
             break;
         case LogLevel.Warn:
             _log.Warn(message);
             break;
         case LogLevel.Fatal:
             _log.Fatal(message);
             break;
         case LogLevel.Error:
             _log.Error(message);
             break;
         default:
             throw new ArgumentOutOfRangeException("level");
     }
 }
コード例 #46
0
        /// <summary>
        /// Ĭ����������캯��
        /// </summary>
        /// <param name="workItem">ϵͳ�������</param>
        public DefaultVirtualCTI(WorkItem workItem)
        {
            this.workItem = workItem;
            this.workItem.Services.Add<IVirtualCTI>(this);
            logger = workItem.Services.Get<ILog>();

            IConfigurationService configService = workItem.Services.Get<IConfigurationService>();
            if (!configService.Exists(sectionPath))
            {
                String errStr = "��ϵͳ�����ļ����ļ�δ�ҵ� \"LightweightCTI\" ���ýڡ�";
                logger.Fatal(errStr);
                throw new Exception(errStr);
            }

            // ��������ļ���
            if (!Directory.Exists(resourceDir))
                Directory.CreateDirectory(resourceDir);
            if (!Directory.Exists(projectsDir))
                Directory.CreateDirectory(projectsDir);

            IConfiguration config = new XMLConfiguration(configService.GetItem(sectionPath));
            ConfigurationInterpreter confInterpreter = new ConfigurationInterpreter(workItem, config);
            confInterpreter.Parse(); // ����������Ϣ�������л�������
        }
コード例 #47
0
 protected void LocateMsDeploy(ILog logger)
 {
     if (_knownMsWebDeployPaths.Any(FileSystem.File.Exists))
     {
         MsWebDeployPath = _knownMsWebDeployPaths.Last(FileSystem.File.Exists);
     }
     else
     {
         if (string.IsNullOrEmpty(MsWebDeployPath))
         {
             logger.Fatal(
                 "Web Deploy could not be located. Ensure that Microsoft Web Deploy has been installed. Locations searched: " +
                 string.Join("\r\n", _knownMsWebDeployPaths));
         }
     }
 }
コード例 #48
0
ファイル: Logger.cs プロジェクト: ddksaku/loreal
        /// <summary>
        /// Logs messages into the log output
        /// </summary>
        /// <param name="message">Message that is sent to the log ouput</param>
        /// <param name="level">Level of the message</param>
        /// <param name="prefix">Prefix of the log file. It is valid on for PackRollingFileAppender</param>
        public static void Log(string message, LogLevel level, LogFilePrefix prefix, bool throwException)
        {
            try
            {
                if (assembly == null)
                {
                    return;
                }

                log = LogManager.GetLogger(assembly, assembly.GetTypes()[0]);

                if (log == null)
                {
                    return;
                }

                   

                //Save additional information
                string logMessage = message + Environment.NewLine;
                ThreadContext.Properties[PrefixFileAppender.LOG_PREFIX] = prefix;

                switch (level)
                {
                    case LogLevel.Info:
                        log.Info(logMessage);
                        break;
                    case LogLevel.Debug:
                        log.Debug(logMessage);
                        break;
                    case LogLevel.Warn:
                        log.Warn(logMessage);
                        break;
                    case LogLevel.Error:
                        log.Error(logMessage);
                        break;
                    case LogLevel.Fatal:
                        log.Fatal(logMessage);
                        break;
                }
            }
            catch (Exception exc)
            {
                if (throwException)
                {
                    throw exc;
                }
            }
        }
コード例 #49
0
ファイル: Logger.cs プロジェクト: camalot/droidexplorer
 /// <summary>
 /// Logs the fatal message.
 /// </summary>
 /// <param name="type">The type.</param>
 /// <param name="message">The message.</param>
 /// <param name="ex">The ex.</param>
 public static void LogFatal( Type type, string message, Exception ex )
 {
     Log = LogManager.GetLogger ( type );
     Log.Fatal ( message, ex );
 }
コード例 #50
0
ファイル: Log.cs プロジェクト: zevinganez/code-o-matic
 /// <summary/>
 public static void EnterFatal(string methodName, string message, string[] argumentNames, object[] arguments, ILog log)
 {
     log.Fatal(MakeEnterMessage(methodName, message, argumentNames, arguments));
 }
コード例 #51
0
ファイル: Bootstrapper.cs プロジェクト: kms/torshify-client
        private void InitializeLogging()
        {
            var fileAppender = new RollingFileAppender();
            fileAppender.File = Path.Combine(AppConstants.LogFolder, "Torshify.log");
            fileAppender.AppendToFile = true;
            fileAppender.MaxSizeRollBackups = 10;
            fileAppender.MaxFileSize = 1024 * 1024;
            fileAppender.RollingStyle = RollingFileAppender.RollingMode.Size;
            fileAppender.StaticLogFileName = true;
            fileAppender.Layout = new PatternLayout("%date{dd MMM yyyy HH:mm} [%thread] %-5level %logger - %message%newline");
            fileAppender.Threshold = Level.Info;
            fileAppender.ActivateOptions();

            var consoleAppender = new CustomConsoleColorAppender();
            consoleAppender.AddMapping(
                new CustomConsoleColorAppender.LevelColors
                {
                    ForeColor = ColoredConsoleAppender.Colors.White | ColoredConsoleAppender.Colors.HighIntensity,
                    BackColor = ColoredConsoleAppender.Colors.Red | ColoredConsoleAppender.Colors.HighIntensity,
                    Level = Level.Fatal
                });
            consoleAppender.AddMapping(
                new CustomConsoleColorAppender.LevelColors
                {
                    ForeColor = ColoredConsoleAppender.Colors.Red | ColoredConsoleAppender.Colors.HighIntensity,
                    Level = Level.Error
                });
            consoleAppender.AddMapping(
                new CustomConsoleColorAppender.LevelColors
                {
                    ForeColor = ColoredConsoleAppender.Colors.Yellow | ColoredConsoleAppender.Colors.HighIntensity,
                    Level = Level.Warn
                });
            consoleAppender.AddMapping(
                new CustomConsoleColorAppender.LevelColors
                {
                    ForeColor = ColoredConsoleAppender.Colors.Green | ColoredConsoleAppender.Colors.HighIntensity,
                    Level = Level.Info
                });
            consoleAppender.AddMapping(
                new CustomConsoleColorAppender.LevelColors
                {
                    ForeColor = ColoredConsoleAppender.Colors.White | ColoredConsoleAppender.Colors.HighIntensity,
                    Level = Level.Info
                });
            consoleAppender.Layout = new PatternLayout("%date{dd MM HH:mm} %-5level - %message%newline");
            #if DEBUG
            consoleAppender.Threshold = Level.All;
            #else
            consoleAppender.Threshold = Level.Info;
            #endif
            consoleAppender.ActivateOptions();

            Logger root;
            root = ((Hierarchy)LogManager.GetRepository()).Root;
            root.AddAppender(consoleAppender);
            root.AddAppender(fileAppender);
            root.Repository.Configured = true;

            BootLogger = LogManager.GetLogger("Bootstrapper");

            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                Exception exception = (Exception)e.ExceptionObject;
                BootLogger.Fatal(exception);
            };

            Application.Current.Dispatcher.UnhandledException += (s, e) =>
            {
                Exception exception = e.Exception;
                BootLogger.Fatal(exception);
            };
        }
コード例 #52
0
ファイル: Provider.cs プロジェクト: tranphuong02/meme-app
        /// <summary>
        ///     Write <paramref name="message"/> to log
        /// </summary>
        /// <param name="message"></param>
        /// <param name="logLevel"></param>
        public void WriteLog(string message, Enums.LogLevels logLevel = Enums.LogLevels.Info)
        {
            switch (logLevel)
            {
                case Enums.LogLevels.Debug:
                    {
                        ThreadContext.Properties["logPath"] = Constants.Paths.Debug;
                    }
                    break;

                case Enums.LogLevels.Info:
                    {
                        ThreadContext.Properties["logPath"] = Constants.Paths.Info;
                    }
                    break;

                case Enums.LogLevels.Warn:
                    {
                        ThreadContext.Properties["logPath"] = Constants.Paths.Warn;
                    }
                    break;

                case Enums.LogLevels.Error:
                    {
                        ThreadContext.Properties["logPath"] = Constants.Paths.Error;
                    }
                    break;

                case Enums.LogLevels.Fatal:
                    {
                        ThreadContext.Properties["logPath"] = Constants.Paths.Fatal;
                    }
                    break;
            }
            _logger = LogManager.GetLogger(GetCaller());
            XmlConfigurator.Configure();
            switch (logLevel)
            {
                case Enums.LogLevels.Debug:
                    {
                        _logger.Debug(message);
                    }
                    break;

                case Enums.LogLevels.Info:
                    {
                        _logger.Info(message);
                    }
                    break;

                case Enums.LogLevels.Warn:
                    {
                        _logger.Warn(message);
                    }
                    break;

                case Enums.LogLevels.Error:
                    {
                        _logger.Error(message);
                    }
                    break;

                case Enums.LogLevels.Fatal:
                    {
                        _logger.Fatal(message);
                    }
                    break;
            }

            LogManager.GetRepository().Shutdown();
        }
コード例 #53
0
ファイル: Main.cs プロジェクト: Dynalon/Rainy
        public static void Main(string[] args)
        {
            // parse command line arguments
            string config_file = "settings.conf";
            string cert_file = null, pvk_file = null;

            int loglevel = 0;
            bool show_help = false;
            bool open_browser = true;

            var p = new OptionSet () {
                { "c|config=", "use config file",
                    (string file) => config_file = file },
                { "v", "increase log level, where -vvvv is highest",
                    v => { if (v != null) ++loglevel; } },
                { "h|help",  "show this message and exit",
                    v => show_help = v != null },
                { "cert=",  "use this certificate for SSL",
                    (string file) => cert_file = file },
                { "pvk=",  "use private key for certSSL",
                    (string file2) => pvk_file = file2 },

                { "b|nobrowser",  "do not open browser window upon start",
                    v => { if (v != null) open_browser = false; } },
            };
            p.Parse (args);

            if (show_help) {
                p.WriteOptionDescriptions (Console.Out);
                return;
            }

            if (!File.Exists (config_file)) {
                Console.WriteLine ("Could not find a configuration file (try the -c flag)!");
                return;
            }

            // set the configuration from the specified file
            Config.Global = Config.ApplyJsonFromPath (config_file);

            DataPath = Config.Global.DataPath;
            if (string.IsNullOrEmpty (DataPath)) {
                DataPath = Directory.GetCurrentDirectory ();
            } else {
                if (!Directory.Exists (DataPath))
                    Directory.CreateDirectory (DataPath);
            }
            SetupLogging (loglevel);
            logger = LogManager.GetLogger ("Main");

            string listen_url = Config.Global.ListenUrl;
            if (string.IsNullOrEmpty (listen_url)) {
                listen_url = "https://localhost:443/";
                logger.InfoFormat ("no ListenUrl set in the settings.conf, using the default: {0}",
                                   listen_url);
            }
            // servicestack expects trailing slash, else error is thrown
            if (!listen_url.EndsWith ("/")) listen_url += "/";

            ConfigureSslCerts (listen_url, cert_file, pvk_file);

            // by default we use the filesystem backend
            if (string.IsNullOrEmpty (Config.Global.Backend)) {
                Config.Global.Backend = "filesystem";
            }

            if (Config.Global.Backend != "filesystem" && string.IsNullOrEmpty (Config.Global.AdminPassword)) {
                logger.Fatal ("An administrator password must be set");
                Environment.Exit (-1);
            }

            open_browser = open_browser && !string.IsNullOrEmpty (Environment.GetEnvironmentVariable ("DISPLAY"));
            open_browser = open_browser && !string.IsNullOrEmpty (Config.Global.AdminPassword);
            open_browser = open_browser && Config.Global.Backend != "filesystem";
            string admin_ui_url = listen_url.Replace ("*", "localhost");
            admin_ui_url += "admin/";

            ComposeObjectGraphDelegate object_graph_composer = ComposeObjectGraph;

            using (var listener = new RainyStandaloneServer (Config.Global.ListenUrl, object_graph_composer)) {

                listener.Start ();
                Uptime = DateTime.UtcNow;

                if (open_browser) {
                    Process.Start (admin_ui_url);
                }

                if (Environment.OSVersion.Platform != PlatformID.Unix &&
                    Environment.OSVersion.Platform != PlatformID.MacOSX) {
                    // we run on windows, can't wait for unix signals
                    Console.WriteLine ("Press return to stop Rainy");
                    Console.ReadLine ();
                    Environment.Exit(0);
                } else {
                    // we run UNIX
                    UnixSignal [] signals = new UnixSignal[] {
                        new UnixSignal(Signum.SIGINT),
                        new UnixSignal(Signum.SIGTERM),
                    };

                    // Wait for a unix signal
                    for (bool exit = false; !exit; )
                    {
                        int id = UnixSignal.WaitAny(signals);

                        if (id >= 0 && id < signals.Length)
                        {
                            if (signals[id].IsSet) exit = true;
                            logger.Debug ("received signal, exiting");
                        }
                    }
                }
            }
        }
コード例 #54
0
ファイル: Connection.cs プロジェクト: sstraus/xdcc-grabscher
        public override void Connect()
        {
            _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType + "(" + Hostname + ":" + Port + ")");

            _isConnected = false;
            using (_tcpClient = new TcpClient())
            {
                _tcpClient.ReceiveTimeout = (MaxData > 0 ? Settings.Instance.DownloadTimeoutTime : Settings.Instance.ServerTimeoutTime) * 1000;

                try
                {
                    _log.Info("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") start");
                    _tcpClient.Connect(Hostname, Port);
                    _isConnected = true;
                }
                catch (SocketException ex)
                {
                    _errorCode = (SocketErrorCode) ex.ErrorCode;
                    _log.Error("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") : " + ((SocketErrorCode) ex.ErrorCode), ex);
                }
                catch (Exception ex)
                {
                    _log.Fatal("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ")", ex);
                }

                if (_isConnected)
                {
                    _log.Info("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") connected");

                    using (NetworkStream stream = _tcpClient.GetStream())
                    {
                        // we just need a writer if reading in text mode
                        if (MaxData == 0)
                        {
                            _writer = new StreamWriter(stream) {NewLine = "\r\n", AutoFlush = true};
                        }

                        FireConnected();

                        _allowRunning = true;
                        try
                        {
                            #region BINARY READING

                            if (MaxData > 0)
                            {
                                using (var reader = new BinaryReader(stream))
                                {
                                    Int64 missing = MaxData;
                                    Int64 max = Settings.Instance.DownloadPerReadBytes;
                                    byte[] data = null;
                                    do
                                    {
                                        try
                                        {
                                            data = reader.ReadBytes((int) (missing < max ? missing : max));
                                        }
                                        catch (ObjectDisposedException)
                                        {
                                            break;
                                        }
                                        catch (SocketException ex)
                                        {
                                            _errorCode = (SocketErrorCode) ex.ErrorCode;
                                            if (_errorCode != SocketErrorCode.InterruptedFunctionCall)
                                            {
                                                _log.Fatal("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading: " + (_errorCode), ex);
                                            }
                                        }
                                        catch (IOException ex)
                                        {
                                            if (ex.InnerException is SocketException)
                                            {
                                                var exi = (SocketException) ex.InnerException;
                                                _errorCode = (SocketErrorCode) exi.ErrorCode;
                                                _log.Fatal("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading: " + (_errorCode), ex);
                                            }
                                            else
                                            {
                                                _log.Fatal("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading", ex);
                                            }
                                            break;
                                        }
                                        catch (Exception ex)
                                        {
                                            _log.Fatal("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading", ex);
                                            break;
                                        }

                                        if (data != null && data.Length != 0)
                                        {
                                            FireDataBinaryReceived(data);
                                            missing -= data.Length;
                                        }
                                        else
                                        {
                                            _log.Warn("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") no data received");
                                            break;
                                        }
                                    } while (_allowRunning && missing > 0);
                                }
                            }

                                #endregion

                                #region TEXT READING

                            else
                            {
                                using (var reader = new StreamReader(stream))
                                {
                                    int failCounter = 0;
                                    string data = "";
                                    do
                                    {
                                        try
                                        {
                                            data = reader.ReadLine();
                                        }
                                        catch (ObjectDisposedException)
                                        {
                                            break;
                                        }
                                        catch (SocketException ex)
                                        {
                                            _errorCode = (SocketErrorCode) ex.ErrorCode;
                                            // we dont need to log this kind of exception, because it is just normal
                                            //Log("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading: " + ((SocketErrorCode)ex.ErrorCode), LogLevel.Exception);
                                        }
                                        catch (IOException ex)
                                        {
                                            if (ex.InnerException is SocketException)
                                            {
                                                var exi = (SocketException) ex.InnerException;
                                                _errorCode = (SocketErrorCode) exi.ErrorCode;
                                                // we dont need to log this kind of exception, because it is just normal
                                                //Log("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading: " + ((SocketErrorCode)exi.ErrorCode), LogLevel.Exception);
                                            }
                                            else
                                            {
                                                _log.Fatal("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading", ex);
                                            }
                                            break;
                                        }
                                        catch (Exception ex)
                                        {
                                            _log.Fatal("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading", ex);
                                            break;
                                        }

                                        if ( /*data != "" && */data != null)
                                        {
                                            if (data != "")
                                            {
                                                failCounter = 0;
                                                FireDataTextReceived(data);
                                            }
                                        }
                                        else
                                        {
                                            failCounter++;
                                            if (failCounter > Settings.Instance.MaxNoDataReceived)
                                            {
                                                _log.Warn("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") no data received");
                                                break;
                                            }
                                            data = "";
                                        }
                                    } while (_allowRunning);
                                }
                            }

                            #endregion

                            Disconnect();
                        }
                        catch (ObjectDisposedException)
                        {
                            // this is ok...
                        }

                        _log.Info("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") end");
                    }
                }

                FireDisconnected(_errorCode);
            }

            _tcpClient = null;
            _writer = null;
        }
コード例 #55
0
ファイル: Log.cs プロジェクト: zevinganez/code-o-matic
 /// <summary/>
 public static void ExceptionFatal(Exception exception, string methodName, string message, ILog log)
 {
     log.Fatal(MakeExceptionMessage(methodName, message), exception);
 }
コード例 #56
0
        private void App_Start(object sender, StartupEventArgs e)
        {
            if (!SingleInstance.Start())
            {
                System.Windows.MessageBox.Show("The P99 Auction Assistant is already running.");
                Application.Current?.Shutdown();
                return;
            }

            var launchedByWindows = e.Args.Any(arg => arg.Equals(ClientController.StartMinimizedArgumentFlag, StringComparison.CurrentCultureIgnoreCase));

            //global settings
            IGlobalSettings _globalSettings = new GlobalSettings();

            //load logging
            log4net.GlobalContext.Properties["StartMode"] = launchedByWindows ? "SILENT" : "USER";
            LoggerConfiguration.Setup(_globalSettings);
            _logger = log4net.LogManager.GetLogger("P99AuctionAssistant");

            //client changable settings
            IClientSettings _clientSettings = ClientSettings.Load();
           
            //server communications 
            IDataDispatcher dispatcher = new SignalRDataDispatcher(_logger, _clientSettings.ApiKey, _globalSettings.ServiceUrlBase,_globalSettings.DispatchRetryCount);

            //setup the logging utility
            try
            {
                notifyIcon = (TaskbarIcon) this.FindResource("NotifyIcon");
                _balloonController = new BalloonHelper(notifyIcon);
                //create the controller and start the application

                _controller = new ClientController(_clientSettings, _globalSettings, _balloonController, _logger, dispatcher,this);
                _controller.ApplicationShutDownRequested += this.Controller_ApplicationShutDownRequested;

                //wireup the notify icon
                if (notifyIcon != null)
                    notifyIcon.DataContext = _controller.NotificationModel;

                _controller.StartApplication(launchedByWindows);
            }
            catch (Exception ex)
            {
                if (_logger != null)
                {
                    _logger.Fatal("A fatal error occured during primary execution", ex);
                    MessageBox.Show("A fatal error occured, the Auction Assistant will now close. See the log for details.", "Fatal Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                System.Environment.Exit(1);
            }
        }
コード例 #57
0
ファイル: Log.cs プロジェクト: zevinganez/code-o-matic
 /// <summary/>
 public static void LeaveFatal(string methodName, string message, bool hasReturnValue, object returnValue, ILog log)
 {
     log.Fatal(MakeLeaveMessage(methodName, message, hasReturnValue, returnValue));
 }
コード例 #58
0
ファイル: Log.cs プロジェクト: zevinganez/code-o-matic
 /// <summary>
 /// Log a message object with the <see cref="F:log4net.Core.Level.Fatal"/> level.
 /// </summary>
 /// <param name="message">The message object to log.</param>
 /// <param name="log">The log.</param>
 /// <overloads>Log a message object with the <see cref="F:log4net.Core.Level.Fatal"/> level.</overloads>
 /// <remarks>
 /// 	<para>
 /// This method first checks if this logger is <c>FATAL</c>
 /// enabled by comparing the level of this logger with the
 /// <see cref="F:log4net.Core.Level.Fatal"/> level. If this logger is
 /// <c>FATAL</c> enabled, then it converts the message object
 /// (passed as parameter) to a string by invoking the appropriate
 /// <see cref="T:log4net.ObjectRenderer.IObjectRenderer"/>. It then
 /// proceeds to call all the registered appenders in this logger
 /// and also higher in the hierarchy depending on the value of the
 /// additivity flag.
 /// </para>
 /// 	<para><b>WARNING</b> Note that passing an <see cref="T:System.Exception"/>
 /// to this method will print the name of the <see cref="T:System.Exception"/>
 /// but no stack trace. To print a stack trace use the
 /// <see cref="M:log4net.ILog.Fatal(System.Object,System.Exception)"/> form instead.
 /// </para>
 /// </remarks>
 /// <seealso cref="M:log4net.ILog.Fatal(System.Object,System.Exception)"/>
 /// <seealso cref="P:log4net.ILog.IsFatalEnabled"/>
 public static void Fatal(object message, ILog log)
 {
     log.Fatal(message);
 }
コード例 #59
0
ファイル: Global.asax.cs プロジェクト: Fernando-Beltran/a2m
        protected void Application_Start()
        {
            try
            {
                AreaRegistration.RegisterAllAreas();
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                log4net.Config.XmlConfigurator.Configure();
                Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
                GlobalConfiguration.Configure(WebApiConfig.Register);

                HttpConfiguration config = GlobalConfiguration.Configuration;
                config.Formatters.JsonFormatter.SerializerSettings.Formatting =
                    Newtonsoft.Json.Formatting.Indented;

                var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["a2mConnectionString"].ConnectionString;
                var ResultsPaginateSize = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ResultsPaginateSize"]);

                BdUpLogger BdUpLogger = new BdUpLogger();

                var upgrader =
                    DeployChanges.To
                        .SqlDatabase(connectionString)
                        .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly()).LogTo(BdUpLogger)
                        .Build();

                var result = upgrader.PerformUpgrade();

                if (!result.Successful)
                {
                    Log.Debug("A2M Not started succesfully due dbUp problem");
                    StartedSuccesfully = false;
                }
                else
                {

                    Log.Debug("A2M started succesfully");
                    StartedSuccesfully = true;
                }
            }
            catch (Exception ex)
            {
                StartedSuccesfully = false;
                Log.Fatal("Unable to start A2M", ex);
            }
        }
コード例 #60
0
ファイル: Log.cs プロジェクト: zevinganez/code-o-matic
 /// <summary>
 /// Log a message object with the <see cref="F:log4net.Core.Level.Fatal"/> level including
 /// the stack trace of the <see cref="T:System.Exception"/> passed
 /// as a parameter.
 /// </summary>
 /// <param name="message">The message object to log.</param>
 /// <param name="exception">The exception to log, including its stack trace.</param>
 /// <param name="log">The log.</param>
 /// <remarks>
 /// See the <see cref="M:log4net.ILog.Fatal(System.Object)"/> form for more detailed information.
 /// </remarks>
 /// <seealso cref="M:log4net.ILog.Fatal(System.Object)"/>
 /// <seealso cref="P:log4net.ILog.IsFatalEnabled"/>
 public static void Fatal(object message, Exception exception, ILog log)
 {
     log.Fatal(message, exception);
 }