@Nikkuz39

NLog правильная настройка в приложении C#?

1. Класс NLog
public void Logger()
        {
            var logger = LogManager.GetCurrentClassLogger();
            try
            {
                var config = new ConfigurationBuilder()
                   .SetBasePath(System.IO.Directory.GetCurrentDirectory())
                   .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                   .Build();

                using var servicesProvider = new ServiceCollection()
                    .AddTransient<DepartmentWithMaxSalary>() // Runner is the custom class
                    .AddLogging(loggingBuilder =>
                    {
                        loggingBuilder.ClearProviders();
                        loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Debug);
                        loggingBuilder.AddNLog(config);
                    }).BuildServiceProvider();

                var runner = servicesProvider.GetRequiredService<DepartmentWithMaxSalary>();
                runner.GetDepartmentWithMaxSalary();
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Stopped program because of exception");
                throw;
            }
            finally
            {
                LogManager.Shutdown();
            }
        }


2. Класс который я хочу логировать:
public class DepartmentWithMaxSalary
    {
        private readonly ILogger logger;

        public DepartmentWithMaxSalary(ILogger<DepartmentWithMaxSalary> log)
        {
            logger = log;
        }

        private String GetDatabaseConnectionString()
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                    .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                    .AddJsonFile("appsettings.json")
                    .Build();

            return configuration.GetConnectionString("DefaultConnection");
        }

        private List<Employee> DepartmentWithHighestSalary()
        {
            List<Employee> employees = new List<Employee>();

            string storedProcedureNameInSql = "DepartmentWithHighestSalary";

            using (SqlConnection connection = new SqlConnection(GetDatabaseConnectionString()))
            {
                try
                {
                    connection.Open();

                    using (SqlCommand command = new SqlCommand(storedProcedureNameInSql, connection))
                    {
                        command.CommandType = CommandType.StoredProcedure;

                        SqlDataReader reader = command.ExecuteReader();

                        if (reader != null)
                        {
                            while (reader.Read())
                            {
                                Employee employee = new Employee();
                                Department department = new Department();

                                department.Id = reader.IsDBNull(0) ? 0 : reader.GetInt32(0);
                                department.Name = reader.IsDBNull(1) ? "" : reader.GetString(1);
                                employee.Salary = reader.IsDBNull(2) ? 0 : reader.GetInt32(2);
                                employee.Name = reader.IsDBNull(3) ? "" : reader.GetString(3);

                                employee.Department = department;

                                employees.Add(employee);
                            }
                            reader.Close();
                        }
                        return employees;
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "Method 'GetDepartmentWithMaxSalary'");
                    return employees;
                }
            }
        }

        public void GetDepartmentWithMaxSalary()
        {
            logger.LogInformation("Call method 'GetDepartmentWithMaxSalary'");

            var employeesList_DepartmentWithMaxSalary = new List<Employee>();
            employeesList_DepartmentWithMaxSalary = DepartmentWithHighestSalary();

            Console.WriteLine("Department with highest salary:");
            Console.WriteLine($"{"Department",-10} {"Salary",-10} {"Name",-10}");
            foreach (Employee employee in employeesList_DepartmentWithMaxSalary)
                Console.WriteLine($"{employee.Department.Name,-10} {employee.Salary,-10} {employee.Name,-10}");
        }
    }


В методе DepartmentWithHighestSalary() может быть проблема с подключением к SQL Server, в связи с чем, там я устанавливаю конструктор "try catch" и в блоке "catch" прописываю "logger.LogError(ex, "Method 'GetDepartmentWithMaxSalary'");", а в методе GetDepartmentWithMaxSalary(), который вызывает метод DepartmentWithHighestSalary(), я прописываю "logger.LogInformation("Call method 'GetDepartmentWithMaxSalary'");".

После чего в методе Main(), я запускаю программу на выполнение:
static void Main(string[] args)
        {
            var logger = new AppLog();
            logger.Logger();
        }


Правильно ли все сделано?
  • Вопрос задан
  • 163 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы