如何防止日志记录混乱你的代码?

时间:2015-11-19 16:49:00

标签: c# logging coding-style

我一直在重构我的一些代码,我无法帮助,但感觉它非常混乱,复杂和令人困惑。在越来越多地研究之后,我开始注意到代码并不是那么复杂,因为它很冗长。

我们正在使用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);
    }

1 个答案:

答案 0 :(得分:-2)

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

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