0

我正在创建一个将运行一堆电机的程序。这些电机与电机控制器接口,我的程序也与之通信。我可以告诉电机控制器定期向我提供有关其状态的数据,以及每个电机的状态和位置。我计划实时查看这些数据,以便操作员可以轻松查看是否有问题,并另外创建此数据的日志,以便之后有人可以返回查看问题所在,以及可能的原因。

问题来了:创建此日志时​​应该考虑什么?我刚从大学毕业,从来没有真正遇到过这样的情况。我当然知道如何创建文件、将数据放入其中并关闭文件,但是数据日志还有更多内容吗?

我已经考虑过的事情是:

  1. 最好为每个数据记录加上时间戳。
  2. 最好对数据进行详细说明,而不是保持二进制。更长的设置时间,更好的最终结果。
  3. 无论程序如何结束,我都必须小心关闭文件。
  4. 我正在使用 C++/CLI,我想知道 MSFT 是否有一些框架可以让这一切变得简单......
  5. 通过测试是否最好在每次收到条目时写入条目,或者最好等到有几个条目并一次写入它们,从而最大限度地减少 CPU/磁盘的使用。

我还应该考虑什么?

4

1 回答 1

0

For something like this, what comes to mind is a comma-separated or tab-separated file. These will be human-readable in notepad, or you can bring it into Excel, and make graphs of the data. (Though I'm sure someone out there will consider CSV or tab-SV to be far away from 'best practice'. However, it's simple to implement, simple to read, and readable in hundreds of apps. That's a pretty darned good practice in my book.)

You can do something similar to this:

FileStream^ textFileStream = gcnew FileStream(logFileName, FileMode::Append, FileAccess::Write, FileShare::Read);
StreamWriter^ textFileWriter = gcnew StreamWriter(textFileStream, Encoding::Unicode);
textFileWriter->AutoFlush = true;
  1. For a timestamp, just dump out DateTime::Now->ToString().
  2. See above for some objects you can use. Use String::Format and send the output to the StreamWriter, that'll give you a verbose, human-readable log.
  3. If you're worried about what happens if your program crashes, don't worry about that too much. The StreamWriter as initialized above will write through to the FileStream as you use it, which will in turn write to the filesystem. This won't do a filesystem-level flush, only a filesystem-level write (the data will be in the OS's write-back cache, to be flushed to disk at some point in the next few seconds), so if the OS crashes, your log file will be incomplete, but a program crash will be handled file.
  4. There are various logging frameworks available for .Net, which you can use from C++/CLI, but I'm not too familiar with them.
  5. Even if you're logging the data each second, it's doubtful that you need to worry about batching up the data. Let's say you had hundreds of motors to write data for: that's what, 1 kilobyte per second? maybe 2? Just write the data out as needed. (If you want to minimize disk/CPU usage, consider just logging the data less frequently, once per 10 seconds or once per minute.)
于 2012-10-10T17:41:57.967 回答