catch (exception e) { syslog (LOG_ERR, "exception: " + e.what()); }
這裏是我嘗試做的,它是不是工作,我已經使用這個系統日誌爲const char *串
string ctos(const char& c){
stringstream s;
s << c;
return s.str();
}
嘗試,但還是輸了
任何幫助將apreciated感謝。
catch (exception e) { syslog (LOG_ERR, "exception: " + e.what()); }
這裏是我嘗試做的,它是不是工作,我已經使用這個系統日誌爲const char *串
string ctos(const char& c){
stringstream s;
s << c;
return s.str();
}
嘗試,但還是輸了
任何幫助將apreciated感謝。
試試這個
catch (exception e)
{
syslog (LOG_ERR, "exception: %s" ,e.what());
}
使用std::string
的構造函數取const char*
,參見reference。所以,你的日誌代碼可以更正如下:
catch (const exception& e) {
syslog (LOG_ERR, (std::string("exception: ") + e.what()).c_str());
}
對不起,沒有工作 – 2010-11-14 08:59:11
@ Angel.King.47:很顯然,syslog將'const char *'作爲第二個參數,因此將調用添加到'c_str()'中。 – vitaut 2010-11-14 09:40:41
+1。謝謝 – 2010-11-14 09:59:25
如果您正在使用syslog(3)
然後它被定義爲:
void syslog(int priority, const char *message, ...);
要麼你想使用printf
類功能syslog
:
catch (const std::exception& e)
{
syslog(LOG_ERR, "exception: %s", e.what());
}
或者你可以轉換到std::string
const char*
,使用std::string::c_str
成員函數:
catch (const std::exception& e)
{
std::string message = std::string("exception: ") + e.what();
syslog(LOG_ERR, message.c_str());
}
另要注意,漁獲物常量引用,否則它是一個很好的機會,實際拋出的異常對象獲得sliced。
您是否正在嘗試將'const char *'(按照您的問題)或'const char'(通過引用傳遞給您的代碼)轉換爲'string'?你的用法還不清楚。 – Johnsyweb 2010-11-14 08:29:30
雖然它與問題無關,但我建議在'catch'中使用'const exception&e',否則你的異常對象將被截斷爲'exception'。 – vitaut 2010-11-14 08:41:45
安全說明:通常,只能在printf或syslog類型格式字符串中使用字符串文字。如果它是一個變量,則將其作爲參數傳遞。在這個例子中,如果有人這樣做了:'throw std :: runtime_error(std :: string(「Bad user input:」)+ user_input)'並且用戶輸入包含格式化攻擊?你的節目將烤麪包! – 2011-04-18 23:37:43