【发布时间】:2022-02-01 06:26:45
【问题描述】:
我是为 c# 代码编写日志的新手...
除了_logger.LogInformation 我不知道要记录什么...
在下面的代码中,谁能告诉我应该写哪些日志?
public IActionResult Index()
{
ViewBag.accounts = GetAccountLists().OrderByDescending(x => x.AccountName).ToList();
_logger.LogInformation("Accessed GetAccountLists() to get account list");
using (var connection = new NpgsqlConnection(connString))
{
var model = new TransactionViewModel();
model.Transactions = connection.Query<Transaction>(@"SELECT t.transaction_id, a.account_name, a.type, t.amount, t.date
FROM account AS a
INNER JOIN transaction AS t ON a.account_id = t.account_id");
_logger.LogInformation("executed a query to get Transactions Information ");
return View(model);
}
}
[HttpPost]
public IActionResult AddTransaction(string account, int amount, DateTime date, string note)
{
using (NpgsqlConnection connection = new NpgsqlConnection(connString))
{
var query = connection.Execute(@"INSERT INTO transaction(account_id,amount,date,note)
SELECT a.account_id,@amount, @date, @note
FROM account AS a
WHERE a.account_name=@account", new {amount, date, note, account});
_logger.LogInformation("executed a query to add New Transaction");
if (query > 0)
{
return View(nameof(AddTransaction));
}
}
return View();
}
public IActionResult AddNewAccount(string account, string type)
{
using (NpgsqlConnection connection = new NpgsqlConnection(connString))
{
var count = connection.ExecuteScalar<int>(@"SELECT * FROM account AS a WHERE a.account_name = @account",
new { account});
_logger.LogInformation("Checking whether there is a account exists with given name, count:- "+count);
if (count == 0)
{
connection.Execute(@"INSERT INTO account(account_name, type)
VALUES(@account, @type)", new { account,type });
_logger.LogInformation("Account Doesn't exists with name:- "+ account+" so adding a account named "+ account);
return View(nameof(AddedView));
}
}
return View(nameof(AddedView));
}
public IActionResult TransactionInfo(int id)
{
using (NpgsqlConnection connection = new NpgsqlConnection(connString))
{
var model = new TransactionInfoViewModel();
model.TransactionsInfo = connection.Query<Transaction>(@"SELECT a.account_name, a.type, DATE(t.date), t.amount, t.note, t.transaction_id
FROM transaction AS t
INNER JOIN account AS a ON t.account_id = a.account_id
WHERE t.transaction_id = @id", new { id });
_logger.LogInformation("Transaction Information With id: "+ id);
return View(model);
}
}
【问题讨论】:
-
你为什么要问?
-
另外,您应该使用
nameof()而不是将 C# 标识符硬编码到您的字符串文字中。 -
connection.ExecuteScalar<int>(@"SELECT * FROM account AS a WHERE a.account_name = @account", new { account } );SELECT COUNT 查询。 -
这些我都知道,我现在更关心日志记录。我应该为此任务编写日志,但是我是新手,不知道应该记录什么...请帮助我
-
@farhan 要求我们告诉你要记录什么就像去 worldbuilding.se 并要求他们告诉你要写什么书。您选择要记录的内容;代码是你的故事,不是我们的
标签: c# logging asp.net-core-mvc ilogger