Esempio n. 1
0
        public void InitializeService(ServiceInitializationParameters initializationParameters)
        {
            Mode = LoggingMode.Service;

            if (initializationParameters == null)
            {
                ServiceName         = "unknown";
                PartitionIdentifier = "unknown";
                ReplicaIdentifier   = "unknown";
                ReplicaLabel        = "R";
            }
            else if (initializationParameters is StatefulServiceInitializationParameters)
            {
                ServiceName         = initializationParameters.ServiceName.OriginalString;
                ReplicaIdentifier   = ((StatefulServiceInitializationParameters)initializationParameters).ReplicaId.ToString();
                PartitionIdentifier = initializationParameters.PartitionId.ToString();
                ReplicaLabel        = "R";
            }
            else if (initializationParameters is StatelessServiceInitializationParameters)
            {
                ServiceName         = initializationParameters.ServiceName.OriginalString;
                ReplicaIdentifier   = ((StatelessServiceInitializationParameters)initializationParameters).InstanceId.ToString();
                PartitionIdentifier = initializationParameters.PartitionId.ToString();
                ReplicaLabel        = "I";
            }
            else
            {
                ServiceName         = initializationParameters.ServiceName.OriginalString;
                ReplicaIdentifier   = "n/a";
                PartitionIdentifier = initializationParameters.PartitionId.ToString();
                ReplicaLabel        = "R";
            }
        }
Esempio n. 2
0
        public static void Log(String log, LoggingMode mode)
        {
            /*switch (mode)
             * {
             *  case LoggingMode.Success:
             *      Console.ForegroundColor = ConsoleColor.Green;
             *      break;
             *
             *  case LoggingMode.Message:
             *      Console.ForegroundColor = ConsoleColor.Yellow;
             *      break;
             *
             *  case LoggingMode.RawData:
             *      Console.ForegroundColor = ConsoleColor.White;
             *      break;
             *
             *  case LoggingMode.Error:
             *  case LoggingMode.Warning:
             *      Console.ForegroundColor = ConsoleColor.Red;
             *      break;
             * }*/

            DateTime now = DateTime.Now;
            String   s   = String.Concat(preStrings[(int)mode], " [", now.Day, "-", now.Month, "-", now.Year, "] [", now.Hour, ":", now.Minute, ":", now.Second, "] ", log);

            stream.WriteLine(s);
            //Console.WriteLine(s);
        }
Esempio n. 3
0
 public static Configuration SetConfig <T>(LoggingMode backMode, string backLogPath)
 {
     if (Config == null)
     {
         return(new Lazy <Configuration>(() =>
         {
             Configuration config = new Configuration
             {
                 LoggingMode = backMode,
                 LogPath = backLogPath.EndsWith(@"/") ? backLogPath : backLogPath + @"/",
                 Dic_type = new Dictionary <string, MethodInfo>(),
                 RunPath = Environment.CurrentDirectory + @"\",
                 ContextMenu = new ContextMenuRegEdit(Environment.CurrentDirectory + @"\", Path.GetFileName(Application.ExecutablePath)),
                 MainObject = Activator.CreateInstance(typeof(T)),
                 Cookies = new CookieContainer()
             };
             Config = config;
             return Config;
         }, LazyThreadSafetyMode.PublicationOnly).Value);
     }
     else
     {
         return(Config);
     }
 }
        public void Log(ILogItem item)
        {
            try
            {
                if (!isInitialized)
                {
                    Initialize();
                }

                if (LoggingMode.Trim().ToUpperInvariant() == LogMode.Asynchronous.ToString().Trim().ToUpperInvariant())
                {
                    AddToQueue(item);
                }
                else
                {
                    foreach (KeyValuePair <int, ILogger> keyValuePair in TargetLoggers)
                    {
                        try
                        {
                            keyValuePair.Value.Log(item);
                            break; // If no exception stop targetting the remaining loggers
                        }
                        catch (Exception)
                        {
                            continue; // If exception occured in the higher priority logger, process next logger
                        }
                    }
                }
            }
            catch (Exception)
            {
                // The exception throw is suppressed so that applications dont get runtime errors
                // if logging fails for any reason
            }
        }
        public static void Initialize(string logFilePath = null, bool useBackgroundTask = false, LoggingSeverity severity = LoggingSeverity.Debug, LoggingMode mode = LoggingMode.File)
        {
            FilePath          = logFilePath.IsNullOrBlankString() ? $@"Logs\{GetCurrentDateString()}.log" : logFilePath;
            Severity          = severity;
            Mode              = mode;
            UseBackgroundTask = useBackgroundTask;

            if (UseBackgroundTask)
            {
                _logQueue       = new ConcurrentQueue <LogEntry>();
                _backgroundTask =
                    Task
                    .Run
                        (() =>
                {
                    while (!_stopLoggingRequested)
                    {
                        if (!_logQueue.TryPeek(out LogEntry lastEntry))
                        {
                            continue;
                        }

                        LogImpl(lastEntry);
                        _logQueue.TryDequeue(out lastEntry);
                    }
                });
            }
        }
Esempio n. 6
0
 /// <summary>
 /// Constructor for logger object. Writes error messages only and not debug information
 /// </summary>
 /// <param name="name">path of the debug file</param>
 /// <param name="outputPath">the path of the debug file</param>
 public Logger(string name, string outputPath)
 {
     _name        = name;
     _outputPath  = outputPath;
     _loggingMode = LoggingMode.Release;
     ConfigureLogger(name, outputPath, "ERROR");
     _log = LogManager.GetLogger(name);
 }
Esempio n. 7
0
        /// <summary>
        /// Log input text to log file
        /// </summary>
        /// <param name="data">text to log</param>
        public void Log(string message, LoggingMode mode = LoggingMode.Normal)
        {
            if (_mode < mode)
            {
                return;
            }

            WriteLine($"{DateTime.Now}\t{message}");
        }
Esempio n. 8
0
 /// <summary>
 /// Changes the level of messages logged out to file
 /// </summary>
 /// <param name="mode"></param>
 public void setMode(LoggingMode mode)
 {
     try
     {
         this._loggingMode = mode;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 9
0
        private static void SetConfig(IOutputService outputService, List <string> parameters)
        {
            //  We must have a key and value.
            if (parameters.Count != 2)
            {
                outputService.WriteError(string.Format("Incorrect syntax. Use: srm config <setting> <value>"));
                return;
            }

            //  Get the setting and value.
            var setting = parameters[0];
            var value   = parameters[1];

            //  Get the config.
            var config = SystemConfigurationProvider.Configuration;

            //  Set the setting.
            if (string.Compare("LoggingMode", setting, StringComparison.OrdinalIgnoreCase) == 0)
            {
                //  Try and parse the setting. If we fail, show an error.
                LoggingMode mode;
                if (Enum.TryParse(value, true, out mode) == false)
                {
                    const LoggingMode allFlags = LoggingMode.Disabled | LoggingMode.Debug | LoggingMode.EventLog | LoggingMode.File;
                    outputService.WriteError(string.Format("Invalid value '{0}'. Acceptible values are: {1}", value, allFlags));
                    return;
                }

                //  Set the logging mode.
                config.LoggingMode = mode;

                //  Save back to the registry.
                SystemConfigurationProvider.Save();

                //  Update the user.
                outputService.WriteSuccess(string.Format("Set LoggingMode to {0}", mode));
            }
            else if (string.Compare("LogPath", setting, StringComparison.OrdinalIgnoreCase) == 0)
            {
                //  Set the path.
                config.LogPath = value;

                //  Save back to the registry.
                SystemConfigurationProvider.Save();

                //  Update the user.
                outputService.WriteSuccess(string.Format("Set LogPath to {0}", value));
            }
            else
            {
                //  Show an error.
                outputService.WriteError(string.Format("{0} is not a valid config setting. Valid settings are LoggingMode and LogPath.", value));
            }
        }
Esempio n. 10
0
            }             // EXPLICTLY FORBID USE OF THE DEFAULT CONSTRUCTOR

            public output(HtmlLogSystem parent, string title, TextOutputManager newOutputWriter, LoggingLevel newLevel, LoggingMode newMode)
            {
                OutputWebInterface.Title     = title;
                OutputWebInterface.CssStyles = parent.HtmlStyle;

                OutputWriter = newOutputWriter;
                OutputLevel  = newLevel;
                OutputMode   = newMode;

                OutputWriter.WriteLine(OutputWebInterface.HtmlHeader);
            }
        public CommunicationServer(IMessageDeserializer messageDeserializer, TimeSpan keepAliveTimeout, int port,
                                   IErrorsMessagesFactory
                                   errorsMessagesFactory, LoggingMode loggingMode, IPAddress address)
        {
            VerboseLogger = new VerboseLogger(LogManager.GetCurrentClassLogger(), loggingMode);

            _errorsMessagesFactory = errorsMessagesFactory;
            _socketListener        = new AsynchronousSocketListener(port, keepAliveTimeout,
                                                                    messageDeserializer, HandleMessage, address
                                                                    );
            _communicationRouter = new CommunicationRouter();
            new Thread(() => _socketListener.StartListening(HandleConnectionError)).Start();
        }
Esempio n. 12
0
        /// <summary>
        /// Initializes target loggers in mode determined by configuration
        /// </summary>
        internal void Initialize()
        {
            logItemsQueue = new ConcurrentQueue <ApplicationLogs>();
            targetLoggers = new Dictionary <int, ILogger>();

            // LogController Level settings
            LoggingConfigurationSetting loggingSetting = CurrentLoggingConfiguration.LoggingConfigurationSetting;

            if (loggingSetting != null)
            {
                this.LoggingMode   = loggingSetting.Mode;
                this.SleepInterval = loggingSetting.SleepInterval;
                this.MaxQueueSize  = loggingSetting.MaxQueueSize;
            }

            // Logger Level settings
            LoggerSettings = CurrentLoggersConfiguration.LoggerConfigurationSettings.Cast <LoggerConfigurationSetting>().ToList();

            try
            {
                // Setup Target loggers from configuration ordered by PriorityOrder
                foreach (LoggerConfigurationSetting configuredLogger in LoggerSettings.OrderBy(o => Convert.ToInt32(o.PriorityOrder)))
                {
                    loggerSequence++;
                    //loggerInstance = dependencyManager.Resolve<ILogger>(configuredLogger.TypeName);
                    loggerInstance.LoggerParameters = configuredLogger.Parameters;
                    loggerInstance.LoggerPriority   = Convert.ToInt32(configuredLogger.PriorityOrder);
                    targetLoggers.Add(loggerSequence, loggerInstance);
                }
            }
            catch (Exception)
            {
                // Do Nothing if logger setup fails
            }

            // If using Asynchronous processing, use another thread for Async Queue processing
            if (LoggingMode.Trim().ToUpperInvariant() == LogMode.Asynchronous.ToString().Trim().ToUpperInvariant())
            {
                processQueueTask = Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        ProcessFromQueue();
                        Thread.Sleep(SleepInterval);
                    }
                }, new CancellationToken(), TaskCreationOptions.LongRunning, TaskScheduler.Default);
            }
            isInitialized = true;
        }
Esempio n. 13
0
        public void InitializePlayer(int id, Guid guid, TeamColor team, PlayerType role, PlayerBoard board,
                                     Location location, LoggingMode loggingMode)
        {
            var factory = new LoggerFactory();

            VerboseLogger = new VerboseLogger(factory.GetPlayerLogger(id), loggingMode);

            Id                      = id;
            Team                    = team;
            Role                    = role;
            PlayerGuid              = guid;
            GameId                  = 0;
            PlayerBoard             = board;
            PlayerBoard.Players[id] = new PlayerInfo(id, team, role, location);
            _stateCoordinator       = new StateCoordinator("", team, role);
        }
Esempio n. 14
0
        /// <summary>
        /// Constructor for logger object. Writes error and/or debug information
        /// </summary>
        /// <param name="name">name of the logger</param>
        /// <param name="outputPath">path of the debug file</param>
        /// <param name="loggingMode">Debug or Release</param>
        public Logger(string name, string outputPath, LoggingMode loggingMode)
        {
            _name        = name;
            _outputPath  = outputPath;
            _loggingMode = loggingMode;

            if (_loggingMode == LoggingMode.Debug)
            {
                ConfigureLogger(name, outputPath, "DEBUG");
            }
            else
            {
                ConfigureLogger(name, outputPath, "ERROR");
            }

            _log = LogManager.GetLogger(name);
        }
Esempio n. 15
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="mode"></param>
 public Logger(string fileName, LoggingMode mode)
 {
     try
     {
         this._logFile = fileName;
         this._loggingMode = mode;
         this._logger = new StreamWriter(_logFile);
     }
     catch (FileLoadException ex)
     {
         throw ex;
     }
     catch (FileNotFoundException ex)
     {
         throw ex;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 16
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="mode"></param>
 public Logger(string fileName, LoggingMode mode)
 {
     try
     {
         this._logFile     = fileName;
         this._loggingMode = mode;
         this._logger      = new StreamWriter(_logFile);
     }
     catch (FileLoadException ex)
     {
         throw ex;
     }
     catch (FileNotFoundException ex)
     {
         throw ex;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        protected void ConfigureLogging(
            LykkeLoggingOptions <T> options,
            LoggingMode mode)
        {
            switch (mode)
            {
            case LoggingMode.Empty:
                ConfigureEmptyLogging(options);
                break;

            case LoggingMode.Debug:
                ConfigureDebugLogging(options);
                break;

            case LoggingMode.Release:
                ConfigureReleaseLogging(options);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(mode), mode, null);
            }
        }
Esempio n. 18
0
 /// <summary>
 /// Constructor for logger object. Writes error messages only and not debug information
 /// </summary>
 /// <param name="name">path of the debug file</param>
 /// <param name="outputPath">the path of the debug file</param>
 public Logger(string name, string outputPath)
 {
     _name        = name;
     _outputPath  = outputPath;
     _loggingMode = LoggingMode.Release;
 }
Esempio n. 19
0
        public Guid AddHeadlinedOutput(string headLine, TextOutputManager newOutputWriter, LoggingLevel newLevel = LoggingLevel.Standard, LoggingMode newMode = LoggingMode.Minimum)
        {
            Guid result = AddOutput(newOutputWriter, newLevel, newMode);

            Header(result, headLine);
            return(result);
        }
Esempio n. 20
0
        public Guid AddOutput(TextOutputManager newOutputWriter, LoggingLevel newLevel = LoggingLevel.Standard, LoggingMode newMode = LoggingMode.Minimum)
        {
            output newOutput = new output(this, Foundation.TimeStamp, newOutputWriter, newLevel, newMode);

            outputs.Add(newOutput);
            return(newOutput.Identifier);
        }
Esempio n. 21
0
 public Diagnostics()
 {
     LogMode = LoggingMode.Console;
 }
Esempio n. 22
0
 /// <summary>
 /// Changes the level of messages logged out to file
 /// </summary>
 /// <param name="mode"></param>
 public void setMode(LoggingMode mode)
 {
     try
     {
         this._loggingMode = mode;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 23
0
 public Diagnostics(LoggingMode logMode, IDatabaseManager databaseManager)
 {
     LogMode          = logMode;
     _databaseManager = databaseManager;
 }
Esempio n. 24
0
 public VerboseLogger(ILogger logger, LoggingMode mode)
 {
     _logger = logger;
     _mode   = mode;
 }
Esempio n. 25
0
 public LoggerAttribute(LoggingMode mode = LoggingMode.Disabled, string logPath = @"./Login/")
 {
     Mode    = mode;
     LogPath = logPath;
 }
Esempio n. 26
0
        public bool checkAllow(LogLevel level, LoggingMode logging = LoggingMode.Null)
        {
            bool allowWrite = false;

            if (logging != LoggingMode.Null) // LOGGING CHECK
            {
                if (level == LogLevel.Info)
                {
                    if (loggingMode == LoggingMode.Mute)
                    {
                        allowWrite = false;
                    }
                    else
                    {
                        allowWrite = true;
                    }
                }
                else if (level == LogLevel.Warning)
                {
                    if (loggingMode == LoggingMode.InfoOnly)
                    {
                        allowWrite = false;
                    }
                    else if (loggingMode == LoggingMode.Essential)
                    {
                        allowWrite = true;
                    }
                    else if (loggingMode == LoggingMode.Verbose)
                    {
                        allowWrite = true;
                    }
                    else if (loggingMode == LoggingMode.Mute)
                    {
                        allowWrite = false;
                    }
                }
                else if (level == LogLevel.Error)
                {
                    if (loggingMode == LoggingMode.InfoOnly)
                    {
                        allowWrite = false;
                    }
                    else if (loggingMode == LoggingMode.Essential)
                    {
                        allowWrite = true;
                    }
                    else if (loggingMode == LoggingMode.Verbose)
                    {
                        allowWrite = true;
                    }
                    else if (loggingMode == LoggingMode.Mute)
                    {
                        allowWrite = false;
                    }
                }
                else if (level == LogLevel.Critical)
                {
                    if (loggingMode == LoggingMode.InfoOnly)
                    {
                        allowWrite = false;
                    }
                    else if (loggingMode == LoggingMode.Essential)
                    {
                        allowWrite = true;
                    }
                    else if (loggingMode == LoggingMode.Verbose)
                    {
                        allowWrite = true;
                    }
                    else if (loggingMode == LoggingMode.Mute)
                    {
                        allowWrite = false;
                    }
                }
                else if (level == LogLevel.Debug)
                {
                    if (loggingMode == LoggingMode.InfoOnly)
                    {
                        allowWrite = false;
                    }
                    else if (loggingMode == LoggingMode.Essential)
                    {
                        allowWrite = false;
                    }
                    else if (loggingMode == LoggingMode.Verbose)
                    {
                        allowWrite = true;
                    }
                    else if (loggingMode == LoggingMode.Mute)
                    {
                        allowWrite = false;
                    }
                }
            }
            else //NORMAL CHECK
            {
                if (level == LogLevel.Info)
                {
                    if (outputMode == OutputMode.Mute)
                    {
                        allowWrite = false;
                    }
                    else
                    {
                        allowWrite = true;
                    }
                }
                else if (level == LogLevel.Warning)
                {
                    if (outputMode == OutputMode.InfoOnly)
                    {
                        allowWrite = false;
                    }
                    else if (outputMode == OutputMode.Essential)
                    {
                        allowWrite = true;
                    }
                    else if (outputMode == OutputMode.Verbose)
                    {
                        allowWrite = true;
                    }
                    else if (outputMode == OutputMode.Mute)
                    {
                        allowWrite = false;
                    }
                }
                else if (level == LogLevel.Error)
                {
                    if (outputMode == OutputMode.InfoOnly)
                    {
                        allowWrite = false;
                    }
                    else if (outputMode == OutputMode.Essential)
                    {
                        allowWrite = true;
                    }
                    else if (outputMode == OutputMode.Verbose)
                    {
                        allowWrite = true;
                    }
                    else if (outputMode == OutputMode.Mute)
                    {
                        allowWrite = false;
                    }
                }
                else if (level == LogLevel.Critical)
                {
                    if (outputMode == OutputMode.InfoOnly)
                    {
                        allowWrite = false;
                    }
                    else if (outputMode == OutputMode.Essential)
                    {
                        allowWrite = true;
                    }
                    else if (outputMode == OutputMode.Verbose)
                    {
                        allowWrite = true;
                    }
                    else if (outputMode == OutputMode.Mute)
                    {
                        allowWrite = false;
                    }
                }
                else if (level == LogLevel.Debug)
                {
                    if (outputMode == OutputMode.InfoOnly)
                    {
                        allowWrite = false;
                    }
                    else if (outputMode == OutputMode.Essential)
                    {
                        allowWrite = false;
                    }
                    else if (outputMode == OutputMode.Verbose)
                    {
                        allowWrite = true;
                    }
                    else if (outputMode == OutputMode.Mute)
                    {
                        allowWrite = false;
                    }
                }
            }

            return(allowWrite);
        }
Esempio n. 27
0
        public Player(ICommunicationClient communicationClient, string gameName, TeamColor preferredColor,
                      PlayerType preferredRole, IErrorsMessagesFactory errorsMessagesFactory, LoggingMode loggingMode, Dictionary <TeamColor, StrategyGroup> strategyGroups)
        {
            CommunicationClient    = communicationClient;
            _gameName              = gameName;
            _preferredColor        = preferredColor;
            _preferredRole         = preferredRole;
            _errorsMessagesFactory = errorsMessagesFactory;
            _strategyGroups        = strategyGroups;

            var factory = new LoggerFactory();

            VerboseLogger = new VerboseLogger(factory.GetPlayerLogger(0), loggingMode);

            _stateCoordinator = new StateCoordinator(gameName, preferredColor, preferredRole);
            new Thread(() => CommunicationClient.Connect(HandleConnectionError, HandleResponse)).Start();
            CommunicationClient.Send(_stateCoordinator.Start());
        }
Esempio n. 28
0
 public Logger(string logFilePath, LoggingMode mode)
 {
     _logFilePath = logFilePath;
     _mode        = mode;
 }
Esempio n. 29
0
 /// <summary>
 /// Constructor for logger object. Writes error and/or debug information
 /// </summary>
 /// <param name="name">name of the logger</param>
 /// <param name="outputPath">path of the debug file</param>
 /// <param name="loggingMode">Debug or Release</param>
 public Logger(string name, string outputPath, LoggingMode loggingMode)
 {
     _name        = name;
     _outputPath  = outputPath;
     _loggingMode = loggingMode;
 }
Esempio n. 30
0
 public ServiceLogger(Guid etwProviderGuid)
 {
     tracingEtw = new EventProvider(etwProviderGuid);
     Mode       = LoggingMode.Generic;
 }
Esempio n. 31
0
        /// <summary>
        /// get logger instance according to LoggingMode
        /// </summary>
        /// <param name="LoggingMode"></param>
        /// <returns></returns>
        private static ILog LogFactory(LoggingMode LoggingMode)
        {
            ILog logger = null;
            switch (LoggingMode)
            {
                case LoggingMode.None:
                    {
                        logger = new NoneLog();
                    } break;

                case LoggingMode.Nlog:
                    {
                        logger = new NLog();
                    } break;

                case LoggingMode.SILog:
                    {
                        // 在Service之中使用SILog必須確保,必須確保SmartInspect程式在Service之前執行

                        bool SmartInspectIsExist = SILog.IsLoggerExist;

                        if (SmartInspectIsExist)
                            logger = new SILog();
                        else
                            logger = new NLog();

                    } break;

                case LoggingMode.Console:
                    {
                        logger = new ConsoleLog();
                    } break;

                case LoggingMode.EventLog:
                    {
                        logger = new EventLog();
                    } break;

                case LoggingMode.FileLog:
                    {
                        logger = new FileLog();
                    } break;

                default: throw new Exception("unknown LoggingMode");
            }
            return logger;
        }
Esempio n. 32
0
 public void InitializeHost(string hostName)
 {
     Mode = LoggingMode.Host;
 }
Esempio n. 33
0
        public GameMaster(GameConfiguration gameConfiguration, ICommunicationClient communicationClient,
                          string gameName, IErrorsMessagesFactory errorsMessagesFactory, LoggingMode loggingMode,
                          IGameMasterMessageFactory gameMasterMessageFactory)
        {
            _gameHost = new GameHost(gameName, gameConfiguration, StartGame);
            _errorsMessagesFactory = errorsMessagesFactory;

            VerboseLogger = new VerboseLogger(LogManager.GetCurrentClassLogger(), loggingMode);

            _messagingHandler = new MessagingHandler(gameConfiguration, communicationClient, HostNewGame,
                                                     gameMasterMessageFactory);
            _messagingHandler.MessageReceived += (sender, args) => MessageHandler(args);
            HostNewGame();
        }