如何登录到浏览器开发人员工具的控制台

时间:2019-03-24 18:30:35

标签: c# asp.net asp.net-web-api asp.net-core log4net

我不知道如何使用ASP.NET/Core登录到浏览器开发人员工具的控制台,我尝试了几种解决方案,但仍然无法从控制器显示浏览器开发人员工具的控制台上的任何日志(我不是在谈论VS控制台。

这是我的代码:

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
    public MyController(Microsoft.Extensions.Logging.ILogger<MyController> logger)
    {
        _logger = logger;
    }


    private readonly Microsoft.Extensions.Logging.ILogger _logger;

    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    [HttpGet]
    public async Task<IActionResult> Get()
    {

        var myData = new MyData();

        Console.WriteLine("Test AAA");
        Debug.WriteLine("Test BBB");

        _logger.LogDebug("Logger Debug");
        _logger.LogInformation("Logger LogInformation");
        _logger.LogError("Logger LogError");
        _logger.LogTrace("Logger LogTrace");

        log.Info("This is a Info message");

        log.Warn("This is a Warning message");

        log.Error("This is an Error message");

        log.Fatal("This is a Fatal message");

        log.Debug("This is a Debug message");

        return Content(myData);
    }
}

如何将这些日志路由到浏览器(Chrome / FireFox)开发人员工具控制台?

2 个答案:

答案 0 :(得分:0)

浏览器日志是通过执行您在该页面中返回的javascript代码来完成的。即使可行,我也认为这不是您想做的事情。

编辑:但是,如果您仍然想这样做,则可以使用loginfo模型和视图中的小javascript脚本来创建自定义视图。像这样:

型号:

public class LogInfo
{
    public string Message { get; set; }
}

查看:

@model Models.LogInfo
<script>console.log("@Model.Message");</script>

控制器:

public IActionResult Index()
{
    LogInfo log = new  LogInfo {
    Message = "Hey Log"
};
    return View(log);
}

答案 1 :(得分:0)

在您曾经用Javascript / Ajax调用Get()的函数中,添加

enum Status { Pending = 0, Done = 1 }
interface Todo { id: number, label: string, status: Status, date?: Date }
const todos: Todo[] = [
    { id: 1, label: 'Task 1', status: Status.Pending },
    { id: 2, label: 'Task 2', status: Status.Pending },
    { id: 1, label: 'Task 1', status: Status.Done },
];
distinct(todos, 'id'); // [{ id: 1, ... status: 1 }, { id: 2, ... status: 0 }]

在Get()方法的末尾,将消息与Ok一起返回

console.log(return);