1. 程式人生 > >The Life with iOS

The Life with iOS

在pch檔案中加入如下程式碼,重定義NSLog   輸出格式為:檔名(行號) 列印資訊

#ifdef DEBUG

#  define NSLog(fmt, ...) do {                                            \
NSString* file = [[NSString alloc] initWithFormat:@"%s", __FILE__]; \
NSLog((@"%@(%d) " fmt), [file lastPathComponent], __LINE__, ##__VA_ARGS__); \
[file release];                                                 \
} while(0)
#else

# define NSLog(...);

在application didFinishLaunchingWithOptions:中的第一行,加入如下三種方法的任意一個,即可將列印資訊定向輸入到檔案

方法1, freopen([@"/tmp/my_logs.txt" fileSystemRepresentation], "w", stderr);  其中,第一個引數為日誌檔案的路徑和檔名,可以由你自己設定,注意,這裡存到了系統根目錄下的tmp下。

方法2, [self redirectNSLog];

在appDelegate中定義如下方法:

- (BOOL)redirectNSLog {
    // Create log file
    [@"" writeToFile:@"/NSLog.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
    id fileHandle = [NSFileHandle fileHandleForWritingAtPath:@"/NSLog.txt"];
    if (!fileHandle)
        NSLog(@"Opening log failed");
        return  NO;
    [fileHandle retain];
    
    // Redirect stderr
    int err = dup2([fileHandle fileDescriptor], STDERR_FILENO);
    if (!err)
        NSLog(@"Couldn't redirect stderr");
        return NO;
    return YES;
}


方法3, [self redirectNSLogToDocumentFolder];

在AppDelegate中定義如下方法:

- (void)redirectNSLogToDocumentFolder{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fileName =[NSString stringWithFormat:@"%@.log",[NSDate date]];
    NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}

通過以上操作,通過開啟或註釋application didFinishLaunchingWithOptions:中的那一句話,即可以決定將日誌寫入檔案還是輸入到控制檯。

相關推薦

The Life with iOS

在pch檔案中加入如下程式碼,重定義NSLog   輸出格式為:檔名(行號) 列印資訊 #ifdef DEBUG #  define NSLog(fmt, ...) do {             

Bring Colorless Wooden Surfaces To Life With The Right Stain Colors

needed ID from beginning infinite open www. ted BE Staining wood is not just a job to make the wooden stuff look appealing but also a

dumped the major features of my life with ADHD and how I manage it | Hacker News

I've had to take a bit of time off work due to being ill, which gave me a great opportunity to sleep a lot and write the longest thing I've

Keeping the smartphone in its place with iOS 12’s Screen Time feature

For years, I have struggled with the burden of owning a smartphone. My two years working as a Carphone Warehouse salesman started the long process of openi

Count the consecutive zero bits (trailing) on the right with multiply and lookup

驗證 %d vol tip inf mat cit number failed 我在網上看到了一點神奇的代碼,用來計算一個數字末尾連續零的個數。 剛好我在優化一個I2C讀寫函數(只寫入I2C特定bit),覺得這個很有用。經過嘗試,確實沒問題。 下面我隆重介紹一下: Coun

[Python] Slice the data with pandas

slice example name [] ant 2.4 int index ram For example we have dataframe like this: SPY AAPL IBM

[Python] Normalize the data with Pandas

orm cnblogs port pre .sh use panda 技術分享 height import os import pandas as pd import matplotlib.pyplot as plt def test_run():

Renewed Red Hat and updated the system with yum up

ren style In cti lba round nor SM then Renewed Red Hat and updated the system with yum update, the following error:Not using downloaded r

R語言統計入門課程推薦——生物科學中的資料分析Data Analysis for the Life Sciences

Data Analysis for the Life Sciences是哈佛大學PH525x系列課程——生物醫學中的資料分析(PH525x series - Biomedical Data Science ),課程全部採用R語言進行統計分析理論教學與實戰。教材採用Rmarkdo

[CSS3] Target HTML Elements not Explicitly set in the DOM with CSS Pseudo Elements

border lose lac imp close election flex size selection Pseudo elements allow us to target elements that are not explicitly set in the

No enclosing instance of type Face is accessible. Must qualify the allocation with an enclosing inst

剛才在練習內部類的時候遇到了這個報錯: No enclosing instance of type Face is accessible. Must qualify the allocation with an enclosing instance of type Face (e.g. x.ne

狀態: 失敗 -測試失敗: Listener refused the connection with the following error: ORA-12505, TNS:listener does

2. 解決:進入資料庫安裝目錄下,找到tnsnames.ora檔案,把其中的service_name改成資料庫正確的sid值,如我的是orcl \network\admin\tnsnames.ora: (ADDRESS = (PROTOCOL = TCP)(HOST

101158J Cover the Polygon with Your Disk

模擬退火+圓與多邊形的面積交 #include"bits/stdc++.h" using namespace std; //圓在多邊形內,或者多邊形在圓內都可以算出 const double eps = 1e-15; const double PI = acos( -1.0

Java 報錯No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing

解決方案:在Person內部類前面新增static,將內部類宣告為靜態內部類。 原因如下:在Java中 (1)類的靜態方法不能直接呼叫動態方法。 (2)類的靜態方法不能初始化內部類(包括該類的內部類,和其他檔案中的內部類)。 (3)類的靜態方法可以初始化其他類檔

ros訊息和服務error:The manifest (with format version 2) must not contain the following tags: run_depend

在按ROS入門教程(點選開啟連結)行進過程中到了執行 rosmsg show beginner_tutorials/Num 命令時,出現提示 The manifest (with format version 2) must not contain the follow

listener refused the connection with the following error:ORA-12519,TNS:no appropriate service handle

oracle監聽出現問題: 出現問題的原因: 因為我想開啟scott使用者然後我又從新配置了一個伺服器名稱,然後原有的監聽就不好使了。 解決原因:我將自己新建的全部刪除。然後從新啟動 注意: 開始–執行–services.msc 找到服務:OracleOraDb10g_home1TNS

[CareerCup] 7.7 The Number with Only Prime Factors 只有質數因子的數字

7.7 Design an algorithm to find the kth number such that the only prime factors are 3,5, and 7. 這道題跟之前LeetCode的那道Ugly Number II 醜陋數之二基本沒有啥區別,具體講解可參見那篇

Image resize on-the-fly with Lambda and S3

A crash course on Serverless with AWS — Image resize on-the-fly with Lambda and S3Handling large images has always been a pain in my side since I started w

CAD: Painting a Clearer Picture of the Heart with Machine Learning

Coronary Artery Disease (CAD) is a condition in which plaque forms on the walls of coronary arteries, causing them to narrow. Eventually, this could lead t

Individual Gain vs the Common Good: Tragedy of the Commons with AI Players

Certain Victory or Optimizing for the Common GoodIn an unregulated version of the tragedy of the commons, players behaving as rational agents should try to