当前位置: 首页>>代码示例>>C#>>正文


C# Logger.Warn方法代码示例

本文整理汇总了C#中NLog.Logger.Warn方法的典型用法代码示例。如果您正苦于以下问题:C# Logger.Warn方法的具体用法?C# Logger.Warn怎么用?C# Logger.Warn使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在NLog.Logger的用法示例。


在下文中一共展示了Logger.Warn方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetJob

        public static Job GetJob(int jobId, Logger defaultLogger)
        {
            Job currentJob;
            using (var repo = new JobRepository())
            {
                defaultLogger.Info("Passed job with ID of {0}", jobId);

                currentJob = repo.GetJobById(jobId);

                if (currentJob == null)
                {
                    defaultLogger.Warn("Job not found");
                    return null;
                }

                defaultLogger.Info("Job found. URL is {0} and branch is {1}", currentJob.Url, currentJob.Branch);

                if (currentJob.State != JobState.Pending)
                {
                    defaultLogger.Warn("Cannot start job. Current state is {0}", currentJob.State);
                    return null;
                }

                repo.UpdateStateForJob(currentJob, JobState.Running);
            }

            return currentJob;
        }
开发者ID:tompoole,项目名称:DeploymentManager,代码行数:28,代码来源:JobHelper.cs

示例2: PokemonSearchCommands

 public PokemonSearchCommands()
 {
     _log = LogManager.GetCurrentClassLogger();
     if (File.Exists(PokemonListFile))
     {
         pokemons = JsonConvert.DeserializeObject<Dictionary<string, SearchPokemon>>(File.ReadAllText(PokemonListFile));
     }
     else
         _log.Warn(PokemonListFile + " is missing. Pokemon abilities not loaded.");
     if (File.Exists(PokemonAbilitiesFile))
         pokemonAbilities = JsonConvert.DeserializeObject<Dictionary<string, SearchPokemonAbility>>(File.ReadAllText(PokemonAbilitiesFile));
     else
         _log.Warn(PokemonAbilitiesFile + " is missing. Pokemon abilities not loaded.");
 }
开发者ID:Chewsterchew,项目名称:NadekoBot,代码行数:14,代码来源:PokemonSearchCommands.cs

示例3: ProcessResults

 public static void ProcessResults(JSONDiff jd, Logger l)
 {
     if (jd.Messages.Any())
     {
         l.Info("--Issues--");
         jd.Messages.ForEach(s2 =>
         {
             var mess = s2.Message?.Trim();
             var exp = s2.Exception?.Trim();
             var m = $"{s2.ProblemType} | {mess} | {exp}";
             m = m.Replace("\r\n", "");
             switch (s2.WarnLevel)
             {
                 case JSONWarnLevel.Warn:
                     l.Warn(m);
                     break;
                 case JSONWarnLevel.Error:
                     l.Error(m);
                     break;
                 case JSONWarnLevel.Fatal:
                     l.Fatal(m);
                     break;
                 default:
                     throw new ArgumentOutOfRangeException();
             }
         });
         l.Info("-----------");
     }
     else
     {
         l.Info("--Success--");
         l.Info("-----------");
     }
 }
开发者ID:andreigec,项目名称:Happy-Diff,代码行数:34,代码来源:Controller.cs

示例4: AutoAssignRoleCommands

            public AutoAssignRoleCommands()
            {
                var _client = NadekoBot.Client;
                this._log = LogManager.GetCurrentClassLogger();
                _client.UserJoined += (user) =>
                {
                    var t = Task.Run(async () =>
                    {
                        try
                        {
                            GuildConfig conf;
                            using (var uow = DbHandler.UnitOfWork())
                            {
                                conf = uow.GuildConfigs.For(user.Guild.Id);
                            }

                            if (conf.AutoAssignRoleId == 0)
                                return;

                            var role = user.Guild.Roles.FirstOrDefault(r => r.Id == conf.AutoAssignRoleId);

                            if (role != null)
                                await user.AddRolesAsync(role);
                        }
                        catch (Exception ex) { _log.Warn(ex); }
                    });
                    return Task.CompletedTask;
                };
            }
开发者ID:Chewsterchew,项目名称:NadekoBot,代码行数:29,代码来源:AutoAssignRoleCommands.cs

示例5: UnitConverterCommands

            static UnitConverterCommands()
            {
                _log = LogManager.GetCurrentClassLogger();

                try
                {
                    var data = JsonConvert.DeserializeObject<List<MeasurementUnit>>(File.ReadAllText("data/units.json")).Select(u => new ConvertUnit()
                    {
                        Modifier = u.Modifier,
                        UnitType = u.UnitType,
                        InternalTrigger = string.Join("|", u.Triggers)
                    }).ToArray();

                    using (var uow = DbHandler.UnitOfWork())
                    {           
                        if (uow.ConverterUnits.Empty())
                        {
                            uow.ConverterUnits.AddRange(data);
                            uow.Complete();
                        }
                    }
                    Units = data.ToList();
                }
                catch (Exception e)
                {
                    _log.Warn("Could not load units: " + e.Message);
                }
            }
开发者ID:Chewsterchew,项目名称:NadekoBot,代码行数:28,代码来源:UnitConversion.cs

示例6: APIProvider

        public APIProvider()
        {
            mdlog = LogManager.GetLogger(Name + ".M");
            tdlog = LogManager.GetLogger(Name + ".T");

            try
            {
                LogManager.Configuration = new XmlLoggingConfiguration(@"Bin/QuantBox.nlog");
            }
            catch(Exception ex)
            {
                tdlog.Warn(ex.Message);
            }

            timerConnect.Elapsed += timerConnect_Elapsed;
            timerDisconnect.Elapsed += timerDisconnect_Elapsed;
            timerAccount.Elapsed += timerAccount_Elapsed;
            timerPonstion.Elapsed += timerPonstion_Elapsed;

            InitCallbacks();
            InitSettings();

            BarFactory = new SmartQuant.Providers.BarFactory();
            status = ProviderStatus.Unknown;
            SmartQuant.Providers.ProviderManager.Add(this);
        }
开发者ID:fouvy,项目名称:OpenQuant-CTP,代码行数:26,代码来源:APIProvider.Provider.cs

示例7: Main

        static void Main()
        {
            _log = LogManager.GetCurrentClassLogger();
            _log.Warn("Service is about to start");
#if DEBUG
            LogManager.GlobalThreshold = LogLevel.Trace;
#endif
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;

            try
            {
                var container = new Container(new SensuClientRegistry());
                var sensuClient = container.GetInstance<ISensuClient>() as ServiceBase;
                
                ServiceBase[] servicesToRun;
                servicesToRun = new ServiceBase[] 
                {
                    sensuClient
                 };

                if (Environment.UserInteractive)
                {
                    RunInteractive(servicesToRun);
                }
                else
                {
                    ServiceBase.Run(servicesToRun);
                }
            }
            catch (Exception exception)
            {
                _log.Error(exception, "Error in startup sensu-client.");
            }
            
        }
开发者ID:dogtbh,项目名称:sensu-client,代码行数:35,代码来源:Program.cs

示例8: Main

 static void Main(string[] args)
 {
     try
     {
         log = LogManager.GetCurrentClassLogger();
         BookListService bls = new BookListService();
         log.Debug("Старт записи в двоичный файл");
             WriteDefaultValues(fileName);
         log.Debug("Окончание записи в двоичный файл");
         log.Debug("Старт чтения данных из двоичног файла");
         bls = ReadDefaultValues(fileName);
         log.Debug("Окончание чтения данных из двоичног файла");
         Book[] find = bls.FindByTag("1999", EnumTag.Year); //Поиск
         foreach (Book b in find)
         Console.WriteLine(b);
         Console.WriteLine("-------------------------");
         Book[] sort = bls.SortBooksByTag(EnumTag.Page);//Сортировка
         foreach (Book b in sort)
             Console.WriteLine(b);
         //log.Warn("Попытка добавить уже существующую книгу");
         //bls.AddBook(sort[0]); 
         bls.RemoveBook(sort[0]);//Удаление книги
         log.Warn("Попытка удаления книги отсутствующей в каталоге");
         bls.RemoveBook(sort[0]);
     }
     catch (Exception e)
     {
         log.Error(e.Message);
     }
     
 }
开发者ID:eduard-posmetuhov,项目名称:ASP.NET.Posmetuhov.Day5,代码行数:31,代码来源:Program.cs

示例9: JokeCommands

            public JokeCommands()
            {
                _log = LogManager.GetCurrentClassLogger();
                if (File.Exists("data/wowjokes.json"))
                {
                    wowJokes = JsonConvert.DeserializeObject<List<WoWJoke>>(File.ReadAllText("data/wowjokes.json"));
                }
                else
                    _log.Warn("data/wowjokes.json is missing. WOW Jokes are not loaded.");

                if (File.Exists("data/magicitems.json"))
                {
                    magicItems = JsonConvert.DeserializeObject<List<MagicItem>>(File.ReadAllText("data/magicitems.json"));
                }
                else
                    _log.Warn("data/magicitems.json is missing. Magic items are not loaded.");
            }
开发者ID:Chewsterchew,项目名称:NadekoBot,代码行数:17,代码来源:JokeCommands.cs

示例10: BotCredentials

        public BotCredentials()
        {
            _log = LogManager.GetCurrentClassLogger();

            try { File.WriteAllText("./credentials_example.json", JsonConvert.SerializeObject(new CredentialsModel(), Formatting.Indented)); } catch { }
            if(!File.Exists(credsFileName))
                _log.Warn($"credentials.json is missing. Attempting to load creds from environment variables prefixed with 'NadekoBot_'. Example is in {Path.GetFullPath("./credentials_example.json")}");
            try
            {
                var configBuilder = new ConfigurationBuilder();
                configBuilder.AddJsonFile(credsFileName, true)
                    .AddEnvironmentVariables("NadekoBot_");

                var data = configBuilder.Build();

                Token = data[nameof(Token)];
                if (string.IsNullOrWhiteSpace(Token))
                    throw new ArgumentNullException(nameof(Token), "Token is missing from credentials.json or Environment varibles.");
                OwnerIds = data.GetSection("OwnerIds").GetChildren().Select(c => ulong.Parse(c.Value)).ToArray();
                LoLApiKey = data[nameof(LoLApiKey)];
                GoogleApiKey = data[nameof(GoogleApiKey)];
                MashapeKey = data[nameof(MashapeKey)];
                OsuApiKey = data[nameof(OsuApiKey)];

                int ts = 1;
                int.TryParse(data[nameof(TotalShards)], out ts);
                TotalShards = ts < 1 ? 1 : ts;

                ulong clId = 0;
                ulong.TryParse(data[nameof(ClientId)], out clId);
                ClientId = clId;

                SoundCloudClientId = data[nameof(SoundCloudClientId)];
                CarbonKey = data[nameof(CarbonKey)];
                var dbSection = data.GetSection("db");
                Db = new DBConfig(string.IsNullOrWhiteSpace(dbSection["Type"]) 
                                ? "sqlite" 
                                : dbSection["Type"], 
                            string.IsNullOrWhiteSpace(dbSection["ConnectionString"]) 
                                ? "Filename=./data/NadekoBot.db" 
                                : dbSection["ConnectionString"]);
            }
            catch (Exception ex)
            {
                _log.Fatal(ex.Message);
                _log.Fatal(ex);
                throw;
            }
            
        }
开发者ID:Chewsterchew,项目名称:NadekoBot,代码行数:50,代码来源:BotCredentials.cs

示例11: RemindCommands

            public RemindCommands()
            {
                _log = LogManager.GetCurrentClassLogger();
                List<Reminder> reminders;
                using (var uow = DbHandler.UnitOfWork())
                {
                    reminders = uow.Reminders.GetAll().ToList();

                    RemindMessageFormat = uow.BotConfig.GetOrCreate().RemindMessageFormat;
                }

                foreach (var r in reminders)
                {
                    try { var t = StartReminder(r); } catch (Exception ex) { _log.Warn(ex); }
                }
            }
开发者ID:Chewsterchew,项目名称:NadekoBot,代码行数:16,代码来源:Remind.cs

示例12: Main

        static void Main(string[] args)
        {            
            ConfigurationItemFactory.Default.Targets.RegisterDefinition("SignalTarget", typeof(SignalTarget));
            Logger = LogManager.GetCurrentClassLogger(typeof(SignalTarget));
            var rnd = new Random((int)DateTime.Now.Ticks);

            for (int i = 0; i < 100; i++) {
                Logger.Trace("Sample trace message from NLog");
                Logger.Debug("Sample debug message from NLog");
                Logger.Info("Sample informational message from NLog");
                Logger.Warn("Sample warning message from NLog");
                Logger.Error("Sample error message from NLog", new Exception("Something bad happened!"));
                Logger.Fatal("Sample fatal error message from NLog");

                var sleep = rnd.Next(20, 250);
                Console.WriteLine(string.Concat("Sleeping...:", sleep, "ms"));
                Thread.Sleep(sleep);
            }

            Console.WriteLine("Logging Complete. Press enter to continue...");
            Console.ReadLine();
        }
开发者ID:Cloudish-OSS,项目名称:Cloudish.LoggingExtensions,代码行数:22,代码来源:Program.cs

示例13: TCPTransport

 public TCPTransport(IPAddress server, int serverPort)
 {
     this.serverIP = server;
     this.serverPort = serverPort;
     logger = LogManager.GetLogger("TCPTransport");
     try
     {
         tcpClient = new TcpClient();
         tcpClient.Connect(server, serverPort);
         this.buff = new BufferedStream(tcpClient.GetStream());
         this.bWriter = new BinaryWriter(buff);
         this.bReader = new BinaryReader(tcpClient.GetStream());
         String message = string.Format("Connected to server :" + server.ToString() + " : " + serverPort);
         logger.Trace(message);
     }
     catch (Exception e)
     {
         String message = string.Format("Could not connect to server :" + server.ToString() + " : " + serverPort);
         logger.Warn("Infinispan.DotNetClient", message);
         throw new TransportException(message, e);
     }
 }
开发者ID:mmarkus,项目名称:dotnet-client,代码行数:22,代码来源:TCPTransport.cs

示例14: TCPTransport

        public TCPTransport(IPEndPoint endPoint)
        {
            ipEndPoint = endPoint;
            logger = LogManager.GetLogger("TCPTransport");
            try
            {
                tcpClient = new TcpClient();
                tcpClient.Connect(ipEndPoint.Address, ipEndPoint.Port);
                // tcpClient.Connect(IPAddress.Loopback, 11222);
                this.buff = new BufferedStream(tcpClient.GetStream());
                this.bWriter = new BinaryWriter(buff);
                this.bReader = new BinaryReader(tcpClient.GetStream());
                String message = string.Format("Connected to server :" + ipEndPoint.Address.ToString() + " : " + ipEndPoint.Port);

                logger.Trace(message);
            }
            catch (Exception e)
            {
                String message = string.Format("Could not connect to server :" + ipEndPoint.Address.ToString() + " : " + ipEndPoint.Port);
                logger.Warn("Infinispan.DotNetClient", message);
                throw new TransportException(message, e);
            }
        }
开发者ID:sunimalr,项目名称:dotnet-client,代码行数:23,代码来源:TCPTransport.cs

示例15: Init

        public void Init(string dirName, string parentProcessId)
        {
            try
            {
                var exeDir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.FullName;
                GlobalDiagnosticsContext.Set("ExeBaseDir", exeDir);
                GlobalDiagnosticsContext.Set("SubDirName", dirName);
                GlobalDiagnosticsContext.Set("ParentProcess", parentProcessId);

                ConfigurationItemFactory.Default.Targets.RegisterDefinition("ServiceManager", typeof(ServiceManagerTarget));
                ConfigurationItemFactory.Default.Targets.RegisterDefinition("ServiceManagerNotification", typeof(NLog.Targets.NullTarget));

                _dirName = dirName;
                _logger = LogManager.GetCurrentClassLogger();

                AppDomain.CurrentDomain.UnhandledException += OnAppDomainUnhandledException;
                TaskScheduler.UnobservedTaskException += OnTaskSchedulerUnobservedTaskException;

                var list = new List<ExtensionInfo>();
                var files = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).GetFiles("*.dll");
                var asmExclusionsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "loader.exclude.txt");
                var exclusions = new HashSet<string>();
                if (File.Exists(asmExclusionsPath))
                    exclusions = new HashSet<string>(
                        File.ReadAllLines(asmExclusionsPath)
                            .Select(s => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, s).ToLower())
                            .Where(File.Exists));

                foreach (var file in files)
                {
                    if (exclusions.Contains(file.FullName.ToLower()))
                        continue;
                    try
                    {
                        var asm = Assembly.Load(Path.GetFileNameWithoutExtension(file.Name));
                        var types = (from t in asm.GetTypes()
                                     where t.GetInterfaces().Any(i => i == typeof(IServerExtension)) && t.IsClass && !t.IsAbstract && t.GetConstructors().Where(i => i.GetParameters().Count() == 0).Any()
                                     select t);
                        var typeMap = (from t in types
                                       select new { Ext = (IServerExtension)Activator.CreateInstance(t) }).ToDictionary(k => k.Ext.ID, v => v.Ext);
                        list.AddRange(
                            typeMap.Values.Select(ext => new ExtensionInfo
                                                         {
                                                             ExtensionID = ext.ID,
                                                             Name = ext.Name,
                                                             Description = ext.Description,
                                                             AssemblyQualifiedName = ext.GetType().AssemblyQualifiedName
                                                         })
                            );
                    }
                    catch (ReflectionTypeLoadException ex)
                    {
                        _logger.Warn("Unable to load: " + file.Name);
                        foreach(var lx in ex.LoaderExceptions)
                            _logger.Warn(" => " + lx.Message);
                        continue;
                    }
                    catch (BadImageFormatException)
                    {
                        continue;
                    }
                }
                _infos = list.ToArray();
                _logger.Info("Obtained info for " + _infos.Length + " available extensions");
            }
            catch (Exception ex)
            {
                _logger.FatalException("Exception while activating exception: ", ex);
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
开发者ID:huoxudong125,项目名称:ServerX,代码行数:72,代码来源:ExtensionActivator.cs


注:本文中的NLog.Logger.Warn方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。