public override void LogEntry(LogEntry entry)
 {
     if (Filter.Writable(entry))
     {
         InnerLogger.LogEntry(entry);
     }
 }
예제 #2
0
        /// <summary>
        /// 重写 LogEntry 方法,交由内联日志记录器记录
        /// </summary>
        /// <param name="entry">要记录的日志条目</param>
        public override void LogEntry(LogEntry entry)
        {
            if (InnerLogger == null)
            {
                throw new InvalidOperationException();
            }

            try
            {
                InnerLogger.LogEntry(entry);
            }
            catch (Exception e)
            {
                try
                {
                    if (ExceptionLogger != null)
                    {
                        ExceptionLogger.LogException(e);
                    }
                }
                catch { }

                throw;
            }
        }
예제 #3
0
 public static void GetGrpcMethods(string serviceName, Type serviceType, IGrpcMarshallerFactory marshallerFactory)
 {
     foreach (GrpcMethodHandlerInfo handler in GrpcReflection.EnumerateServiceMethods(serviceName, serviceType, marshallerFactory))
     {
         Handers.AddOrUpdate(handler.GetHashString(), handler);
         InnerLogger.Log(LoggerLevel.Debug, handler.GetHashString());
     }
 }
예제 #4
0
        public static IApplicationBuilder UseGrpcMonitorProtoFileEnable(this IApplicationBuilder app)
        {
            DirectoryMonitor monitor = new DirectoryMonitor(GrpcServiceMethodFactory.ProtoPath, "*.proto");

            monitor.Change += (string filePath) =>
            {
                InnerLogger.Log(LoggerLevel.Debug, filePath);
                GrpcServiceMethodFactory.ProtoQueue.Enqueue(filePath);
            };
            monitor.Start();
            return(app);
        }
예제 #5
0
        public TException Write <TException>(LogEventLevel level, TException exception)
            where TException : Exception
        {
            if (exception == null)
            {
                throw SelfLogger.Fatal.ArgumentNull(nameof(exception));
            }

            InnerLogger.Write(
                level,
                exception,
                "Throwing exception",
                new Object[0]
                );

            return(exception);
        }
예제 #6
0
        public static Server StartAndRegisterConsul(this Server server)
        {
            server.Start();
            var ports    = server.Ports;
            var srvNames = server.Services.GetServicesName();

            try
            {
                var client = new ConsulClient(p =>
                {
                    p.Address = new Uri("http://127.0.0.1:8500");
                });
                client.Agent.ServiceRegister(new AgentServiceRegistration {
                    Address = "127.0.0.1",
                    Port    = ports.First().BoundPort,
                    Name    = srvNames.First(),
                    Tags    = srvNames.ToArray(),
                    Check   = new AgentServiceCheck {
                        //TTL=TimeSpan.FromSeconds(5),
                        Status   = HealthStatus.Passing,
                        TCP      = "127.0.0.1:50051",
                        Interval = TimeSpan.FromSeconds(5)
                    }
                }).Wait();

                //client.Agent.CheckRegister(new AgentCheckRegistration
                //{
                //    DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1),
                //    TTL = TimeSpan.FromSeconds(ServiceConfig.TCPInterval),
                //    Status = HealthStatus.Passing,
                //    ID = ServiceConfig.GetConsulServiceId() + ":ttlcheck",
                //    ServiceID = ServiceConfig.GetConsulServiceId(),
                //    Name = "ttlcheck"
                //}).Wait();

                client.Dispose();
            }
            catch (Exception ex)
            {
                InnerLogger.Log(LoggerLevel.Error, $"consul Register failed {Environment.NewLine}{ex.ToString()}");
            }


            return(server);
        }
 public async Task Invoke(MiddlewareContext context)
 {
     var _retryAsync = Policy
                       .Handle <Exception>()
                       .RetryAsync(_options.RetryTimes, async(exception, retryCount) =>
     {
         await InnerLogger.LogAsync(LoggerLevel.Error, $"-------第{retryCount}次重试!exception:{exception.Message}");
     });
     // todo:这里设置没有用,还不知道原因;
     var _timeoutAsync = Policy
                         .TimeoutAsync(TimeSpan.FromMilliseconds(_options.TimoutMilliseconds), async(ct, ts, tk, exception) =>
     {
         await InnerLogger.LogAsync(LoggerLevel.Error, $"---------超时.");
     });
     await Policy.WrapAsync(_retryAsync, _timeoutAsync).ExecuteAsync(async() =>
     {
         await _next(context);
     });
 }
예제 #8
0
        public static bool Build(string csPath, string assemblyName)
        {
            var dllFiles = Directory.GetFiles(csPath, "*.cs");

            if (dllFiles.Length == 0)
            {
                return(false);
            }
            List <SyntaxTree> trees = new List <SyntaxTree>();

            foreach (var file in dllFiles)
            {
                // https://www.cnblogs.com/wolf-sun/p/6136482.html
                var csStr = File.ReadAllText(file, encoding: Encoding.GetEncoding("GB2312"));
                trees.Add(CSharpSyntaxTree.ParseText(csStr, encoding: Encoding.UTF8));
            }
            var references2 = new[] {
                MetadataReference.CreateFromFile(Assembly.Load("netstandard, Version=2.0.0.0").Location),
                MetadataReference.CreateFromFile(Assembly.Load("System.Runtime, Version=0.0.0.0").Location),
                MetadataReference.CreateFromFile(Assembly.Load("System.IO, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").Location),
                MetadataReference.CreateFromFile(Assembly.Load("System.Threading.Tasks, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").Location),
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Google.Protobuf.ProtoPreconditions).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(grpc.Channel).Assembly.Location),
            };
            var options     = new CSharpCompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release);
            var compilation = CSharpCompilation.Create(assemblyName, trees, references2, options);
            var result2     = compilation.Emit(Path.Combine(csPath, $"{assemblyName}.dll"), xmlDocumentationPath: Path.Combine(csPath, $"{assemblyName}.xml"));

            //, xmlDocPath: Path.Combine(csPath, $"{assemblyName}.xml")
            //var classSymbol = compilation.GlobalNamespace.GetTypeMembers("C").Single();
            //var docComment = classSymbol.GetDocumentationCommentXml();
            //Console.WriteLine(docComment);

            InnerLogger.Log(
                result2.Success ? LoggerLevel.Debug : LoggerLevel.Error,
                string.Join(",", result2.Diagnostics.Select(d => string.Format("[{0}]:{1}({2})", d.Id, d.GetMessage(), d.Location.GetLineSpan().StartLinePosition)))
                );
            Thread.Sleep(100);
            return(result2.Success);
        }
 /// <summary>
 /// Wrap of <see cref="InnerLogger"/>
 /// </summary>
 public override void CloseNestedAppenders()
 {
     InnerLogger.CloseNestedAppenders();
 }
예제 #10
0
    void SendMessage(TestMessageLevel level, string assemblyName, string message)
    {
        var assemblyText = assemblyName == null ? "" : $"{Path.GetFileNameWithoutExtension(assemblyName)}: ";

        InnerLogger.SendMessage(level, $"[xUnit.net {Stopwatch.Elapsed:hh\\:mm\\:ss\\.ff}] {assemblyText}{message}");
    }
 /// <summary>
 /// The point of stamping the event and hand-over to <see cref="InnerLogger"/>
 /// </summary>
 /// <param name="loggingEvent">event to stamp and pass</param>
 protected override void CallAppenders(LoggingEvent loggingEvent)
 {
     Call(loggingEvent);
     InnerLogger.Log(loggingEvent);
 }
 /// <summary>
 /// Wrap of <see cref="InnerLogger"/>
 /// </summary>
 /// <param name="appender"></param>
 /// <returns></returns>
 public override Appender.IAppender RemoveAppender(Appender.IAppender appender)
 {
     return(InnerLogger.RemoveAppender(appender));
 }
 /// <summary>
 /// Wrap of <see cref="InnerLogger"/>
 /// </summary>
 /// <param name="name"></param>
 /// <returns></returns>
 public override Appender.IAppender RemoveAppender(string name)
 {
     return(InnerLogger.RemoveAppender(name));
 }
 /// <summary>
 /// Wrap of <see cref="InnerLogger"/>
 /// </summary>
 public override void RemoveAllAppenders()
 {
     InnerLogger.RemoveAllAppenders();
 }
예제 #15
0
 /// <summary>
 /// 重写 Dispose 方法,释放内联日志记录器的资源
 /// </summary>
 public override void Dispose()
 {
     InnerLogger.Dispose();
 }
예제 #16
0
        public static bool Generate(string baseDirectory, string protoFile)
        {
            var architecture = RuntimeInformation.OSArchitecture.ToString().ToLower();// 系统架构,x86 x64
            var bin          = string.Empty;
            var os           = string.Empty;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                os  = "windows";
                bin = ".exe";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                os = "linux";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                os = "macosx";
            }
            else
            {
                InnerLogger.Log(LoggerLevel.Error, "该平台不支持.");
                return(false);
            }
            var protocBinPath = Path.Combine(baseDirectory, $"tools/{os}_{architecture}/protoc{bin}");
            var pluginBinPath = Path.Combine(baseDirectory, $"tools/{os}_{architecture}/grpc_csharp_plugin{bin}");
            var csharp_out    = Path.Combine(baseDirectory, $"plugins/.{Path.GetFileNameWithoutExtension(protoFile)}");

            // 创建文件夹
            if (!Directory.Exists(csharp_out))
            {
                Directory.CreateDirectory(csharp_out);
            }
            //protoFile.GetMD5();

            var proto_path  = Path.Combine(baseDirectory, "protos");
            var protoc_args = $" --proto_path={proto_path} --csharp_out {csharp_out} {Path.GetFileName(protoFile)} --grpc_out {csharp_out} --plugin=protoc-gen-grpc={pluginBinPath}";

            Console.WriteLine(protocBinPath + "     " + protoc_args);
            var psi = new ProcessStartInfo(protocBinPath, protoc_args)
            {
                RedirectStandardOutput = true
            };

            //启动
            using (var proc = System.Diagnostics.Process.Start(psi))
            {
                if (proc == null)
                {
                    InnerLogger.Log(LoggerLevel.Debug, "-------------Can not exec.--------------");
                    return(false);
                }
                else
                {
                    var output = proc.StandardOutput.ReadToEnd();

                    InnerLogger.Log(LoggerLevel.Debug, "-------------Start read standard output--------------");
                    InnerLogger.Log(LoggerLevel.Debug, "-------------" + output + "--------------");
                    ////开始读取
                    //using (var sr = proc.StandardOutput)
                    //{
                    //    while (!sr.EndOfStream)
                    //    {
                    //        InnerLogger.Log(LoggerLevel.Debug, sr.ReadLine());
                    //    }

                    //    if (!proc.HasExited)
                    //    {
                    //        proc.Kill();
                    //    }
                    //}
                    InnerLogger.Log(LoggerLevel.Debug, "---------------Read end------------------");
                    InnerLogger.Log(LoggerLevel.Debug, $"Exited Code : {proc.ExitCode}");
                }
                Thread.Sleep(100);
            }
            return(true);
        }
 /// <summary>
 /// Wrap of <see cref="InnerLogger"/>
 /// </summary>
 /// <param name="newAppender"></param>
 public override void AddAppender(Appender.IAppender newAppender)
 {
     InnerLogger.AddAppender(newAppender);
 }
예제 #18
0
 static Logger()
 {
     Instance = new InnerLogger();
 }
        private void SendMessage(TestMessageLevel level, string?filename, string message)
        {
            var fileNameText = string.IsNullOrEmpty(filename) ? string.Empty : $"{filename} ";

            InnerLogger.SendMessage(level, $"[NodeJS TestAdapter {Stopwatch.Elapsed:hh\\:mm\\:ss\\.ff}] {fileNameText}{message}");
        }
 /// <summary>
 /// Wrap of <see cref="InnerLogger"/>
 /// </summary>
 /// <param name="level"></param>
 /// <returns></returns>
 public override bool IsEnabledFor(Level level)
 {
     return(InnerLogger.IsEnabledFor(level));
 }