简体   繁体   中英

How can I send log messages to the Console app using Xcode and c++?

How can I send log messages to Console.app using Xcode and c++? The only code I have access to is the c++ source, not Objective-C. Also, other developers in the shop need to be able to follow log messages using the Mac Console app (Console.app), so using the Xcode console is not an option. I'm basically looking for an NSLog(...) alternative. Something simple like that. Thanks.

If you want to write to the system log, you can use syslog() as follows:

openlog("foo", (LOG_CONS|LOG_PERROR|LOG_PID), LOG_USER);
syslog(priority, "%s", "a message");
closelog();

However, I find it more convenient to write to my own log file which can be read by Console.app. This lets me do fancier formatting than syslog() supports, and I also don't have to hunt for my messages among the many other messages in the system log.

Here's how I do this for a program I'll call "foo":

  1. Get the current user's home directory. You can do this by using getuid() and getpwuid() to get the passwd struct, and analyzing the home directory string from that.
  2. Append "/Library/Logs/foo.log" to the home directory string.
  3. Use that as the path argument to fopen() to create a FILE* for the log file.
  4. Then use standard fprintf(), fflush(), etc. calls to write to the log file.
  5. Close the log file at the end of program execution.

You can see the result of this in Console.app by opening Files > ~/Library/Logs. The file "foo.log" will be there and contain the contents of your logging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM