在 Javascript 中为 Web 应用程序生成日志 [英] Generate logs for web application in Javascript

查看:26
本文介绍了在 Javascript 中为 Web 应用程序生成日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,我想为我的 JS Web 应用程序生成日志,该日志可以作为文件存储在客户端(存储在用户的机器上).

I have a use case in which I would like to generate logs for my JS web application, which could be stored as a file on the client-side (stored on the user's machine).

因此,我想知道在JS中生成日志可以采用什么方法?

Therefore, I want to know that what approach can I follow for generating logs in JS?

推荐答案

如果你的意思是你想从浏览器托管的 JavaScript 代码中做到这一点,恐怕你不能.基于浏览器的 JavaScript 代码无法写入用户计算机上的任意文件.这将是一个巨大的安全问题.

If you mean you want to do this from browser-hosted JavaScript code, I'm afraid you can't. Browser-based JavaScript code can't write to arbitrary files on the user's computer. It would be a massive security problem.

你可以保留一个日志"在网络存储中,但请注意网络存储有大小限制所以你不会想让它变得太大.

You could keep a "log" in web storage, but note that web storage has size limits so you wouldn't want to let it grow too huge.

这是添加到本地存储日志的准系统日志记录功能:

Here's a barebones logging function that adds to a log in local storage:

function log(...msgs) {
    // Get the current log's text, or "" if there isn't any yet
    let text = localStorage.getItem("log") || "";
    // Add this "line" of log data
    text += msgs.join(" ") + "
";
    // Write it back to local storage
    localStorage.setItem("log", text);
}

显然,您可以通过多种不同的方式(日志级别、日期/时间日志记录等)在此基础上进行构建.

Obviously you can then build on that in a bunch of different ways (log levels, date/time logging, etc.).

这篇关于在 Javascript 中为 Web 应用程序生成日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆