D
D
DVoropaev2019-10-02 22:35:36
linux
DVoropaev, 2019-10-02 22:35:36

How to pull logs from syslog in C++?

What is the best way to get logs from the /var/log/syslog file from such and such to such and such time in C++?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Cheremisin, 2019-10-02
@leahch

The problem with the logs is that they are not specified, from the word - at all. The log file format is different depending on the logging system, syslog does one, rsyslog does the second, Apache does the third, and so on. and there is still a rotation of these logs, which is launched by the crown (usually).
So I'm afraid you will have to write the log parser yourself, or look for a ready-made library in c / c ++. Libraries do not come to mind, but there are log-collector programs like logstash that can convert logs to some common denominator and throw them into a database, for example. So the logs are the easiest to pull out of the database, especially in C.

V
Vitaly Karasik, 2019-10-03
@vitaly_il1

As already mentioned, there is a rotation of the logs, so in the general case it is difficult to pull out for a certain period of time, because. you need to find logs for previous periods.
Options:
- add all syslog logs to the database - the most popular today is Elasticsearch. She has an API in all languages, there are no problems to take logs from there for a period of time.
For her, there is a log shipper that can parse and send logs to Elasticsearch
- limit yourself to a special case - the rotation occurs once a week, the format of the names of the old syslog is such and such.
- or write everything yourself - in my opinion, it makes no sense

R
Roman, 2019-10-03
@myjcom

Oct  2 23:39:48 dvrh systemd-resolved[562]: Server returned er....

for this kind of primitive.
#include <iostream>
#include <string>
#include <fstream>
#include <sys/utsname.h>

std::string getTimestamp(const std::string& line)
{
  auto pos = line.rfind(' ');
  return line.substr(pos + 1, line.size() - pos);
}

int main(int argc, char* argv[])
{
  if(argc < 3)
  {
    std::cerr << "usage: file timestamp timestamp\n/var/log/syslog 11:00:00 12:00:00\n";
    exit(EXIT_FAILURE);
  }

  struct utsname uts;

  if(uname(&uts) == -1)
  {
    exit(EXIT_FAILURE);
  }

  if(std::ifstream flog(argv[1]); flog)
  {
    std::string start{argv[2]};
    std::string stop {argv[3]};
    std::string line;

    while(getline(flog, line))
    {
      std::string header = getTimestamp(line.substr(0, line.find(uts.nodename) - 1));
      if(header >= start && header <= stop)
      {
        std::cout << line << "\n";
      }
    }
  }
  else
  {
    std::cerr << "Cannot open file: " << argv[1];
  }
}

if also with a date - a little more.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question