Exemplo n.º 1
0
 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");
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// 输出普通日志
        /// </summary>
        /// <param name="level"></param>
        /// <param name="format"></param>
        /// <param name="args"></param>
        private void Log(LoggerLevel level, string format, params object[] args)
        {
            switch (level)
            {
            case LoggerLevel.Debug:
                _Logger4net.DebugFormat(format, args);
                break;

            case LoggerLevel.Info:
                _Logger4net.InfoFormat(format, args);
                break;

            case LoggerLevel.Warn:
                _Logger4net.WarnFormat(format, args);
                break;

            case LoggerLevel.Error:
                _Logger4net.ErrorFormat(format, args);
                break;

            case LoggerLevel.Fatal:
                _Logger4net.FatalFormat(format, args);
                break;
            }
        }
        public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
        {
            if (args == null)
            {
                return;
            }
            if (0 == args.Length)
            {
                base.TraceEvent(eventCache, source, eventType, id, format, args);
            }


            if (string.IsNullOrWhiteSpace(source))
            {
                var frame = GetTracingStackFrame(new StackTrace());
                source = frame.GetMethod().DeclaringType.FullName;

                if (source == null)
                {
                    source = this.GetType().FullName;
                }
            }

            //_log = LogManager.GetLogger(source);
            switch (eventType)
            {
            case TraceEventType.Critical:
                _log.FatalFormat(format, args);
                break;

            case TraceEventType.Error:
                _log.ErrorFormat(format, args);
                break;

            case TraceEventType.Information:
                _log.InfoFormat(format, args);
                break;

            case TraceEventType.Resume:
            case TraceEventType.Start:
            case TraceEventType.Stop:
            case TraceEventType.Suspend:
            case TraceEventType.Transfer:
            case TraceEventType.Verbose:
                _log.DebugFormat(format, args);
                break;

            case TraceEventType.Warning:
                _log.WarnFormat(format, args);
                break;
            }
        }
Exemplo n.º 4
0
 public void log_a_fatal_event_containing(string message, params object[] args)
 {
     logger.FatalFormat(message, args);
 }
Exemplo n.º 5
0
 public void FatalFormat(string format, object arg0)
 {
     log.FatalFormat(format, arg0);
 }
Exemplo n.º 6
0
 /// <summary>
 /// Logs the fatal message.
 /// </summary>
 /// <param name="type">The type.</param>
 /// <param name="provider">The provider.</param>
 /// <param name="format">The format.</param>
 /// <param name="args">The args.</param>
 public static void LogFatal( Type type, IFormatProvider provider, string format, params object[] args )
 {
     Log = LogManager.GetLogger ( type );
     Log.FatalFormat ( provider, format, args );
 }
Exemplo n.º 7
0
 public override void FatalFormat(string msg, params object[] args)
 {
     innerLogger.FatalFormat(msg, args);
 }
Exemplo n.º 8
0
 public static void FatalFormat(IFormatProvider provider, string format, params object[] args)
 {
     Log.FatalFormat(provider, format, args);
 }
Exemplo n.º 9
0
        /// <summary>
        ///     Initializes library.
        /// </summary>
        static XInputDll()
        {
            Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

            Log.InfoFormat("Library loaded by process {0} [{1}]",
                Process.GetCurrentProcess().ProcessName,
                Process.GetCurrentProcess().MainWindowTitle);

            var myself = Assembly.GetExecutingAssembly().GetName();
            var myPath = Assembly.GetExecutingAssembly().Location;
            var myName = Path.GetFileName(myPath);

            Log.InfoFormat("Initializing library {0} [{1}]", myName, myself.Version);

            try
            {
                var basePath = BasePath;
                Log.DebugFormat("ScpToolkit bin path: {0}", basePath);
                var controlPath = ScpControlPath;
                Log.DebugFormat("ScpControl bin path: {0}", controlPath);

                // resolve assembly dependencies
                AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
                {
                    var asmName = new AssemblyName(args.Name).Name;
                    var asmPath = Path.Combine(basePath, string.Format("{0}.dll", asmName));

                    Log.DebugFormat("Loading assembly {0} from {1}", asmName, asmPath);

                    return Assembly.LoadFrom(asmPath);
                };

                var scpControl = Assembly.LoadFrom(controlPath);
                var scpProxyType = scpControl.GetType("ScpControl.ScpProxy");

                Proxy = Activator.CreateInstance(scpProxyType);

                Proxy.Start();
            }
            catch (Exception ex)
            {
                Log.FatalFormat("Error during library initialization: {0}", ex);
                return;
            }

            // if no custom path specified by user, use DLL in system32 dir
            var xinputPath = !string.IsNullOrEmpty(XInputDllPath) && File.Exists(XInputDllPath)
                ? XInputDllPath
                : Path.Combine(Environment.SystemDirectory, myName);
            Log.DebugFormat("Original XInput DLL path: {0}", xinputPath);

            NativeDllHandle = Kernel32Natives.LoadLibrary(xinputPath);

            if (NativeDllHandle == IntPtr.Zero)
            {
                Log.FatalFormat("Couldn't load native DLL: {0}", new Win32Exception(Marshal.GetLastWin32Error()));
                return;
            }

            Log.Info("Library initialized");
        }
Exemplo n.º 10
0
 /// <summary>
 /// Logs a formatted message string with the <see cref="F:log4net.Core.Level.Fatal"/> level.
 /// </summary>
 /// <param name="format">A String containing zero or more format items</param>
 /// <param name="arg0">An Object to format</param>
 /// <param name="log">The log.</param>
 /// <remarks>
 /// 	<para>
 /// The message is formatted using the <c>String.Format</c> method. See
 /// <see cref="M:System.String.Format(System.String,System.Object[])"/> for details of the syntax of the format string and the behavior
 /// of the formatting.
 /// </para>
 /// 	<para>
 /// This method does not take an <see cref="T:System.Exception"/> object to include in the
 /// log event. To pass an <see cref="T:System.Exception"/> use one of the <see cref="M:log4net.ILog.Fatal(System.Object,System.Exception)"/>
 /// methods instead.
 /// </para>
 /// </remarks>
 /// <seealso cref="M:log4net.ILog.Fatal(System.Object)"/>
 /// <seealso cref="P:log4net.ILog.IsFatalEnabled"/>
 public static void FatalFormat(string format, object arg0, ILog log)
 {
     log.FatalFormat(format, arg0);
 }
Exemplo n.º 11
0
 /// <summary>
 /// Logs a formatted message string with the <see cref="F:log4net.Core.Level.Fatal"/> level.
 /// </summary>
 /// <param name="provider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information</param>
 /// <param name="format">A String containing zero or more format items</param>
 /// <param name="args">An Object array containing zero or more objects to format</param>
 /// <param name="log">The log.</param>
 /// <remarks>
 /// 	<para>
 /// The message is formatted using the <c>String.Format</c> method. See
 /// <see cref="M:System.String.Format(System.String,System.Object[])"/> for details of the syntax of the format string and the behavior
 /// of the formatting.
 /// </para>
 /// 	<para>
 /// This method does not take an <see cref="T:System.Exception"/> object to include in the
 /// log event. To pass an <see cref="T:System.Exception"/> use one of the <see cref="M:log4net.ILog.Fatal(System.Object)"/>
 /// methods instead.
 /// </para>
 /// </remarks>
 /// <seealso cref="M:log4net.ILog.Fatal(System.Object,System.Exception)"/>
 /// <seealso cref="P:log4net.ILog.IsFatalEnabled"/>
 public static void FatalFormat(IFormatProvider provider, string format, object[] args, ILog log)
 {
     log.FatalFormat(provider, format, args);
 }
Exemplo n.º 12
0
        public static async Task <Rootobject> InvokeRequestResponseService(string[,] timeSeriesValues, AnomalyDetectionInput inputParameters = null)
        {
            Log.Info("InvokeRequestResponseService");
            if (inputParameters != null)
            {
                Log.Info("Detected input parameters.");
                FillInputParameters(inputParameters);
                if (Log.IsInfoEnabled)
                {
                    PrintInputParameters();
                }
            }


            using (var client = new HttpClient())
            {
                var scoreRequest = new
                {
                    Inputs = new Dictionary <string, StringTable>()
                    {
                        {
                            "input1",
                            new StringTable()
                            {
                                ColumnNames = new string[] { "timestamp", "count" },
                                // Values = new string[,] {  { "", "0" },  { "", "0" },  }
                                Values = timeSeriesValues
                            }
                        },
                    },
                    GlobalParameters = InputParameters
                };
                string apiKey = ConfigurationManager.AppSettings["AnomalyDetectionApiKey"]; // Replace this with the API key for the web service
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
                string url = ConfigurationManager.AppSettings["AnomalyDetectionWebServiceUrl"];
                Log.InfoFormat("Url {0}", url);
                client.BaseAddress = new Uri(url);

                // WARNING: The 'await' statement below can result in a deadlock if you are calling this code from the UI thread of an ASP.Net application.
                // One way to address this would be to call ConfigureAwait(false) so that the execution does not attempt to resume on the original context.
                // For instance, replace code such as:
                //      result = await DoSomeTask()
                // with the following:
                //      result = await DoSomeTask().ConfigureAwait(false)


                HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);

                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();

                    Log.InfoFormat("Result: {0}", result);


                    if (!string.IsNullOrEmpty(result))
                    {
                        Rootobject ro = JsonConvert.DeserializeObject <Rootobject>(result);

                        Results r = ro.Results;

                        Value v = r.output1.value;

                        string[][] values = v.Values;

                        StringBuilder finalMatrixStrb   = new StringBuilder();
                        StringBuilder columnNamesBuffer = new StringBuilder();
                        foreach (string cn in v.ColumnNames)
                        {
                            columnNamesBuffer.Append(string.Format("{0},", cn));
                        }
                        string columnNames = columnNamesBuffer.ToString();
                        if (columnNames.EndsWith(","))
                        {
                            columnNames = columnNames.Remove(columnNames.LastIndexOf(','), 1);
                        }
                        finalMatrixStrb.AppendLine(columnNames);


                        for (int i = 0; i < values.Length; i++)
                        {
                            StringBuilder eachRow = new StringBuilder();
                            for (int j = 0; j < values[i].Length; j++)
                            {
                                string s  = values[i][j];
                                string si = string.Format("{0},", s);
                                eachRow.Append(si);
                            }
                            string finalRowTemp = eachRow.ToString();
                            if (finalRowTemp.EndsWith(","))
                            {
                                finalRowTemp = finalRowTemp.Remove(finalRowTemp.LastIndexOf(','), 1);
                            }
                            finalMatrixStrb.AppendLine(finalRowTemp);
                        }



                        string resultGuid = System.Guid.NewGuid().ToString("N");
                        string fileName   = string.Format("{0}.csv", resultGuid);

                        if (!string.IsNullOrEmpty(inputParameters.OutputFileName))
                        {
                            fileName = inputParameters.OutputFileName;
                        }
                        File.WriteAllText(fileName, finalMatrixStrb.ToString());

                        string opr = r.output2.value.Values[0][0];


                        JObject jo = JObject.Parse(opr);

                        if (jo != null)
                        {
                            JToken jt       = jo.Last;
                            var    children = jo.Children();
                            string imgb64   = null;
                            int    i        = 0;
                            foreach (JProperty j in children)
                            {
                                if (j.Name == "Graphics Device")
                                {
                                    imgb64 = j.Value.First.Value <string>();

                                    if (!string.IsNullOrEmpty(imgb64))
                                    {
                                        Image ig = Base64ToImage(imgb64);
                                        //string guid = System.Guid.NewGuid().ToString("N");
                                        string fn = Path.GetFileNameWithoutExtension(fileName);
                                        fileName = string.Format("{0}-{1}.png", fn, i++);
                                        ig.Save(fileName);
                                    }
                                }
                            }

                            //var v = imstr.FirstOrDefault();
                        }
                        return(ro);
                    }
                }
                else
                {
                    Log.FatalFormat("The request failed with status code: {0}", response.StatusCode);

                    // Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
                    Log.Fatal(response.Headers.ToString());

                    string responseContent = await response.Content.ReadAsStringAsync();

                    Log.Fatal(responseContent);
                }
            }

            Log.Info("End InvokeRequestResponseService");
            return(null);
        }
Exemplo n.º 13
0
        private static string[,] ReadCSVFile(string inputFile)
        {
            try
            {
                IList <string> errors           = new List <string>();
                IList <string> validTimeRecord  = new List <string>();
                IList <string> validValueRecord = new List <string>();
                bool           hasHeaders       = HasHeaders(inputFile);
                using (TextReader reader = File.OpenText(inputFile))
                {
                    var csv = new CsvReader(reader);
                    if (hasHeaders)
                    {
                        csv.Configuration.HasHeaderRecord = true;
                    }
                    while (csv.Read())
                    {
                        try
                        {
                            var      time     = csv.GetField <DateTime>(0);
                            bool     validRow = false;
                            DateTime timeField;
                            if (csv.TryGetField(0, out timeField))
                            {
                                double valueField;
                                if (csv.TryGetField(1, out valueField))
                                {
                                    validRow = true;
                                    validTimeRecord.Add(timeField.ToString("s"));
                                    validValueRecord.Add(valueField.ToString());
                                }
                            }

                            if (!validRow)
                            {
                                errors.Add(csv.Row.ToString());
                            }
                        }catch (Exception yx)
                        {
                            Log.ErrorFormat("Error parsing CSV field. Omitting field. {0}", yx);
                        }
                    }//while

                    if (errors.Count > 0)
                    {
                        File.WriteAllLines("badrecords.log", errors.ToArray());
                    }

                    int MAX_COUNT = validTimeRecord.Count;
                    string[,] bigArr = new string[MAX_COUNT, 2];
                    for (int i = 0; i < MAX_COUNT; i++)
                    {
                        bigArr[i, 0] = validTimeRecord[i];
                        bigArr[i, 1] = validValueRecord[i];
                    }

                    return(bigArr);
                }
            }catch (Exception ex)
            {
                Log.FatalFormat("Error while reading csv file {0}.", ex.Message);

                throw ex;
            }
        }
Exemplo n.º 14
0
 public static void FatalFormatted(string format, params object[] args)
 {
     log.FatalFormat(format, args);
 }
Exemplo n.º 15
0
 public void Fatal(string message, params object[] formatting)
 {
     // don't need to check for enabled at this level
     _logger.FatalFormat(decorate_message_with_audit_information(message), formatting);
 }
Exemplo n.º 16
0
 /// <summary>
 /// Logs a formatted message string with the <see cref="F:log4net.Core.Level.Fatal"/> level.
 /// </summary>
 /// <param name="format">A String containing zero or more format items</param>
 /// <param name="args">An Object array containing zero or more objects to format</param>
 /// <param name="log">The log.</param>
 /// <overloads>Log a formatted message string with the <see cref="F:log4net.Core.Level.Fatal"/> level.</overloads>
 /// <remarks>
 /// 	<para>
 /// The message is formatted using the <c>String.Format</c> method. See
 /// <see cref="M:System.String.Format(System.String,System.Object[])"/> for details of the syntax of the format string and the behavior
 /// of the formatting.
 /// </para>
 /// 	<para>
 /// This method does not take an <see cref="T:System.Exception"/> object to include in the
 /// log event. To pass an <see cref="T:System.Exception"/> use one of the <see cref="M:log4net.ILog.Fatal(System.Object)"/>
 /// methods instead.
 /// </para>
 /// </remarks>
 /// <seealso cref="M:log4net.ILog.Fatal(System.Object,System.Exception)"/>
 /// <seealso cref="P:log4net.ILog.IsFatalEnabled"/>
 public static void FatalFormat(string format, object[] args, ILog log)
 {
     log.FatalFormat(CultureInfo.InvariantCulture, format, args);
 }
Exemplo n.º 17
0
        private static void RunService(CommandLineParser parser, Action<StringDictionary> environment, ILog logger)
        {
            if (ServiceEnvironmentManagementEx.IsServiceDisabled(parser.Target))
            {
                logger.ErrorFormat("The service '{0}' is disabled. Please enable the service.",
                    parser.Target);
                return;
            }

            var service = new ServiceController(parser.Target);
            try
            {

                if (service.Status != ServiceControllerStatus.Stopped)
                {
                    logger.ErrorFormat(
                        "The service '{0}' is already running. The profiler cannot attach to an already running service.",
                    parser.Target);
                    return;
                }

                // now to set the environment variables
                var profilerEnvironment = new StringDictionary();
                environment(profilerEnvironment);

                var serviceEnvironment = new ServiceEnvironmentManagement();

                try
                {
                    serviceEnvironment.PrepareServiceEnvironment(
                        parser.Target,
                            parser.ServiceEnvironment,
                        (from string key in profilerEnvironment.Keys
                         select string.Format("{0}={1}", key, profilerEnvironment[key])).ToArray());

                    // now start the service
                    var old = service;
                    service = new ServiceController(parser.Target);
                    old.Dispose();

                    if (parser.Target.ToLower().Equals("w3svc"))
                    {
                        // Service will not automatically start
                        if (! TerminateCurrentW3SvcHost(logger) ||
                            !ServiceEnvironmentManagementEx.IsServiceStartAutomatic(parser.Target))
                        {
                            service.Start();
                        }
                    }
                    else
                    {
                        service.Start();
                    }
                    logger.InfoFormat("Service starting '{0}'", parser.Target);
                    service.WaitForStatus(ServiceControllerStatus.Running, parser.ServiceStartTimeout);
                    logger.InfoFormat("Service started '{0}'", parser.Target);
                }
                catch (InvalidOperationException fault)
                {
                    logger.FatalFormat("Service launch failed with '{0}'", fault);
                }
                finally
                {
                    // once the serice has started set the environment variables back - just in case
                    serviceEnvironment.ResetServiceEnvironment();
                }

                // and wait for it to stop
                service.WaitForStatus(ServiceControllerStatus.Stopped);
                logger.InfoFormat("Service stopped '{0}'", parser.Target);

                // Stopping w3svc host
                if (parser.Target.ToLower().Equals("w3svc"))
                {
                    logger.InfoFormat("Stopping svchost to clean up environment variables for w3svc", parser.Target);
                    if (ServiceEnvironmentManagementEx.IsServiceStartAutomatic(parser.Target))
                    {
                        logger.InfoFormat("Please note that the 'w3svc' service may automatically start");
                    }
                    TerminateCurrentW3SvcHost(logger);
                }
            }
            finally
            {
                service.Dispose();
            }
        }
Exemplo n.º 18
0
 public void FatalFormat(System.IFormatProvider provider, string format, params object[] args)
 {
     _logger.FatalFormat(provider, format, args);
 }
Exemplo n.º 19
0
 public static void FatalFormat(string format, object arg0)
 {
     Logger.FatalFormat(format, arg0);
 }
Exemplo n.º 20
0
 public void FatalFormat(string format, params object[] args)
 {
     _logger.FatalFormat(format, args);
 }
Exemplo n.º 21
0
 /// <summary>
 /// Logs the fatal message.
 /// </summary>
 /// <param name="type">The type.</param>
 /// <param name="format">The format.</param>
 /// <param name="args">The args.</param>
 public static void LogFatal( Type type, string format, params object[] args )
 {
     Log = LogManager.GetLogger ( type );
     Log.FatalFormat ( CultureInfo.CurrentCulture, format, args );
 }
Exemplo n.º 22
0
 public void WarnFormat(string format, params object[] args)
 {
     netLog.FatalFormat(format, args);
 }
Exemplo n.º 23
0
 public static void FatalFormat(string format, object arg0)
 {
     _log4netInstance.FatalFormat(format, arg0);
 }