如何防止日志记录扰乱代码

本文关键字:代码 记录 何防止 日志 | 更新日期: 2023-09-27 18:22:48

我一直在重构我的一些代码,我忍不住觉得它非常混乱、复杂和令人困惑。在对它进行了越来越多的研究之后,我开始注意到代码与其说复杂,不如说冗长。

我们使用NLog,并向调试日志提供非常详细的输出,因为应用程序非常容易出现故障,我们正在努力做到非常彻底。

下面是一个比较简单的方法的例子

    [HttpGet]
    public ActionResult Zendesk(long? id)
    {
        if (!GlobalVariables.AllSyncSettings.SyncEnabled || !GlobalVariables.AllSyncSettings.ZdSyncEnabled)
            return Json(new { Enabled = "False" });
        if (id == null || id == 0)
            return Json(new { Error = "Missing or malformed ticket ID." }, AG);
        if (CheckZdIdExists((long)id))
            return Json(new { status = "error, in queue." }, AG);
        GlobalVariables.TicketsInQueue.Add((long)id);
        Log("-------------- STARTING NEW CASE [ZENDESK]["+ id +"] --------------");
        var zdHelper = new ZendeskHelpers();
        var zdTicket = zdHelper.GetTicketById((long)id);
        if (zdTicket == null)
        {
            Log("--------------- ENDING CASE [ZENDESK][" + id + "] ---------------");
            GlobalVariables.TicketsInQueue.Remove((long)id);
            return Json(new { Error = "Error fetching ticket" }, AG);
        }
        var sfHelper = new SalesForceHelpers();
        if (!sfHelper.checkTicketOwner(zdTicket))
        {
            Warn(id + " | Case generation not necessary. Ticket doesn't meet criteria.");
            Log("--------------- ENDING CASE [ZENDESK][" + id + "] ---------------");
            GlobalVariables.TicketsInQueue.Remove((long)id);
            return Json(new { success = "case was not generated" }, AG);
        }
        Log(id + " | Generating SalesForce case for Zendesk");
        var sfCase = sfHelper.GenerateCase(zdTicket);
        if (sfCase == null)
        {
            Warn(id + " | Case was not generated successfully. Cannot continue.");
            Log("--------------- ENDING CASE [ZENDESK][" + id + "] ---------------");
            GlobalVariables.TicketsInQueue.Remove((long)id);
            return Json(new { Error = "Case was not generated successfully. Cannot continue." }, AG);
        }
        GetZDAttachments(zdHelper, sfHelper, (long)id, sfCase);
        if (!zdTicket.Status.ToLower().Contains("closed") && ZendeskHelpers.GetCustomField(zdTicket, ZdCustomFields.SfCaseNo) == null)
            zdHelper.SetSfId(zdTicket, sfCase.CaseNumber);
        Log("--------------- ENDING CASE [ZENDESK][" + id + "] ---------------");
        GlobalVariables.TicketsInQueue.Remove((long)id);
        return Json(new { SFCase = sfCase }, AG);
    }

如何防止日志记录扰乱代码

您的代码充满了条件语句(if太多),这就是冗长的原因。你应该用多态性替换你的条件句。在这里提供了一篇很好的文章

http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html