Q: How do i print the current function and line number?
A: We can print the current function and line number by using some precompiled macros as printing parameters when printing. Such as:
NSLog(@"%s:%d obj=%@", __func__, __LINE__, obj);
NSLog (@ "%s:%d obj=%@", __func__, __line__, self); Output style: //2015-01-06 17:13:17.852 justtest[15079:613] //-[viewcontroller viewdidload]:38 obj=< Viewcontroller:0x109949aa0>
which func and line are precompiled macros that are replaced by the current function and the current line number, respectively, at compile time. Here are some macros that are commonly used for printing logs.
macro |
description |
__func__ |
print the current function or method, C string |
__line__ |
Print the current line number, integer |
__file__ |
Print the current file path, C string |
__pretty_function__ |
print the current function or method (contains parameter types in C + +), C string |
Q: How do I print a class name, message name, and current stack information?
A: You can use the following methods to dynamically obtain this information at run time.
code |
description |
nsstringfromselector (SEL) |
Get the name of selector |
nsstringfromselector (_cmd) |
Gets the current method name |
nsstringfromclass ([object class]) |
Gets the class name of object |
[nsthread callstacksymbols] |
Gets the stack of the current thread, which is a nsarry that contains all the function names in the stack. |
q: How to print a log to a file
A: You can use the Freopen function to redirect standard output and standard error files. Because the printf function prints to standard output (stdout), the NSLog function prints to the standard error (STDERR). Redirecting standard output (STDOUT) and standard error (STDERR) to a file will cause them to print the log into a file.
freopen("/tmp/log.txt", "a+", stdout);freopen("/tmp/log.txt", "a+", stderr);
iOS Development-Log printing (common)