戻る

デバッグの方法

JavaScript

Console API

Firebugを知らない方のために簡単に説明します。FirebugとはFirefoxのアドオン(拡張機能)です。インストールすることで、表示しているページのHTMLやCSSを表示・編集したり、JavaScriptのデバッグを行うことができます。 ダウンロードはAdd-ons for Firefoxからできます。

console APIはFirebugの機能のひとつで、コンソールにメッセージを表示することができます。 また、これはGoogle Chromeのデベロッパーツールでも表示することができます。 使い方はとても簡単で、scriptタグの中に命令文を書くだけです。

<script type="text/javascript">
console.log( 'APIの解説はじめるよー' );    // ←コレ
</script>

console.log()

コンソールにメッセージを表示します。変数を渡せば変数の中身が表示されます。オブジェクトを渡せばオブジェクトの中身が表示されます。

var hoge = 'ほげ';
console.log( hoge );
var fuga = jQuery( 'body' );
console.log( fuga );

console.debug()

var hoge = 'ほげ';
console.debug( hoge );

console.info() / console.warn() / console.error()

これらも基本的にはconsole.debug()と同様の機能です。異なる点は、アイコンと色で視覚的にメッセージを区別することができます。

var hoge = 'ほげ';
console.debug( hoge );

console.trace()

JavaScriptのスタックトレースを出力します。分かりやすく言うと、コールした時点で呼ばれていた関数名を表示します。

function testFunc1( arg ) {
	var i = arg + 1;
	return testFunc2( i );
}
function testFunc2( arg ) {
	var i = arg + 2;
	return testFunc3( i );
}
function testFunc3( arg ) {
	console.trace();	// この時点で呼ばれていた関数を順に表示します
	var i = arg + 3;
	return i;
}
function sampleFunc( arg ) {
	var i = arg;
	return testFunc1( i );
}
sampleFunc( 1 );

console.time() / console.timeEnd()

処理の実行時間を計測します。console.time() でタイマーをスタートし、console.timeEnd() でタイマーをストップします。 表示される単位はミリ秒です。

// 同じ引数 "sample" を持つ timeEndまでが測定されます
console.time( 'sample' );
for ( var i = 0; i < 1000; i++ ) {
	window.document.write( i );
}
console.timeEnd( 'sample' );

紹介したもの以外にも便利な機能があります

ここだけでは書ききれませんでしたが、その他にも関数単位での処理時間を計測できるconsole.profile() や、同じ行が呼ばれた回数を計測するconsole.count() などがあります。 興味のある方はFirebugWikiに公式ドキュメントがあるので見てみてはいかがでしょうか。

アルパカの具

PHP

PHPが発するエラーの種類

プログラムを作っていると、避けて通れないのがエラーです。最初から正しく動くプログラムを作るのは難しいものです。どのようにして、エラーを見つけ出し修正することができるでしょうか。ここでは、エラーについての傾向と対策、修正方法のためのヒントを紹介します。

はじめに、PHPでプログラムを作っているときに遭遇するエラーの種類について紹介します。

パースエラー(Parse Error)

プログラムの文法ミス、構文上の誤りが問題で発生するエラーです。命令文の最後のセミコロンを書き忘れたり、文字列の引用符を閉じ忘れたりするといった原因が考えられます。PHPインタプリタはパースエラーが発生するとプログラムの動作を停止させます。また、予約語を関数・定数名に使用するとパースエラーになります。文法に間違いがないのにエラーが出たときは予約語を使っていないか確かめてみましょう。

致命的なエラー(Fatal Error)

プログラムの内容に関して重大な問題があるときに発生するエラーです。定義されていない関数を呼び出したり、メモリが不足するなどの原因が考えられます。こうした致命的な問題があると、PHPインタプリタはプログラムの動作を停止させます。

警告(Warning)

関数を呼び出すときに引数の数を間違えたとか、存在しないファイルを読み取り専用モードで開こうとした場合などに発生する警告です。上の2つのエラーと違って、PHPインタプリタはプログラムの動作を停止することはありません。

注意(Notice)

注意を促すメッセージです。変数を初期化せずに使った場合などに表示されます。

厳格注意(Strict Notice)

コーディングスタイルについてのアドバイスを表示します。PHP4とPHP5で変更された機能や、推奨されない関数を使った場合に表示されます。

互換性の注意(Deprecated)

実行時に出る注意です。これを有効にすると、将来のバージョンで動作しなくなるコードについて警告を受け取ることができます。

エラー表示の切り替え

上記のようなエラーのうち、例えば、警告(Warning)や注意(Notice)といったものは、アプリケーションの開発時には有用ですが、実際にサービスとして公開を始めた後には表示されては困るものです。そこで、PHPでは設定ファイル(php.ini)の構成ディレクティブのerror_reportingに定数を指定することで特定のタイプのエラーだけを報告させることができます。

設定ファイルの構成ディレクティブのerror_reportingに指定するのは、E_ALL(厳格注意以外のすべてのエラー用)、E_PARSE(パースエラー)、E_ERROR(致命的なエラー)、E_WARNING(警告)、E_NOTICE(注意)、E_STRICT(厳格注意)、E_DEPRECATED(互換性注意)といった定数値です。

C:\xampp\php\php.ini

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Error handling and logging ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

; This directive informs PHP of which errors, warnings and notices you would like
; it to take action for. The recommended way of setting values for this
; directive is through the use of the error level constants and bitwise
; operators. The error level constants are below here for convenience as well as
; some common settings and their meanings.
; By default, PHP is set to take action on all errors, notices and warnings EXCEPT
; those related to E_NOTICE and E_STRICT, which together cover best practices and
; recommended coding standards in PHP. For performance reasons, this is the
; recommend error reporting setting. Your production server shouldn't be wasting
; resources complaining about best practices and coding standards. That's what
; development servers and development settings are for.
; Note: The php.ini-development file has this setting as E_ALL | E_STRICT. This
; means it pretty much reports everything which is exactly what you want during
; development and early testing.
;
; Error Level Constants:
; E_ALL             - All errors and warnings (includes E_STRICT as of PHP 6.0.0)
; E_ERROR           - fatal run-time errors
; E_RECOVERABLE_ERROR  - almost fatal run-time errors
; E_WARNING         - run-time warnings (non-fatal errors)
; E_PARSE           - compile-time parse errors
; E_NOTICE          - run-time notices (these are warnings which often result
;                     from a bug in your code, but it's possible that it was
;                     intentional (e.g., using an uninitialized variable and
;                     relying on the fact it's automatically initialized to an
;                     empty string)
; E_STRICT          - run-time notices, enable to have PHP suggest changes
;                     to your code which will ensure the best interoperability
;                     and forward compatibility of your code
; E_CORE_ERROR      - fatal errors that occur during PHP's initial startup
; E_CORE_WARNING    - warnings (non-fatal errors) that occur during PHP's
;                     initial startup
; E_COMPILE_ERROR   - fatal compile-time errors
; E_COMPILE_WARNING - compile-time warnings (non-fatal errors)
; E_USER_ERROR      - user-generated error message
; E_USER_WARNING    - user-generated warning message
; E_USER_NOTICE     - user-generated notice message
; E_DEPRECATED      - warn about code that will not work in future versions
;                     of PHP
; E_USER_DEPRECATED - user-generated deprecation warnings
;
; Common Values:
;   E_ALL & ~E_NOTICE  (Show all errors, except for notices and coding standards warnings.)
;   E_ALL & ~E_NOTICE | E_STRICT  (Show all errors, except for notices)
;   E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR  (Show only errors)
;   E_ALL | E_STRICT  (Show all errors, warnings and notices including coding standards.)
; Default Value: E_ALL & ~E_NOTICE
; Development Value: E_ALL | E_STRICT
; Production Value: E_ALL & ~E_DEPRECATED
; http://php.net/error-reporting
error_reporting = E_ALL | E_STRICT

; This directive controls whether or not and where PHP will output errors,
; notices and warnings too. Error output is very useful during development, but
; it could be very dangerous in production environments. Depending on the code
; which is triggering the error, sensitive information could potentially leak
; out of your application such as database usernames and passwords or worse.
; It's recommended that errors be logged on production servers rather than
; having the errors sent to STDOUT.
; Possible Values:
;   Off = Do not display any errors 
;   stderr = Display errors to STDERR (affects only CGI/CLI binaries!)   
;   On or stdout = Display errors to STDOUT
; Default Value: On
; Development Value: On
; Production Value: Off
; http://php.net/display-errors
display_errors = On

; The display of errors which occur during PHP's startup sequence are handled
; separately from display_errors. PHP's default behavior is to suppress those
; errors from clients. Turning the display of startup errors on can be useful in
; debugging configuration problems. But, it's strongly recommended that you
; leave this setting off on production servers.
; Default Value: Off
; Development Value: On
; Production Value: Off
; http://php.net/display-startup-errors
display_startup_errors = On

; Besides displaying errors, PHP can also log errors to locations such as a
; server-specific log, STDERR, or a location specified by the error_log
; directive found below. While errors should not be displayed on productions
; servers they should still be monitored and logging is a great way to do that.
; Default Value: Off
; Development Value: On
; Production Value: On
; http://php.net/log-errors
log_errors = On

; Set maximum length of log_errors. In error_log information about the source is
; added. The default is 1024 and 0 allows to not apply any maximum length at all.
; http://php.net/log-errors-max-len
log_errors_max_len = 1024

; Do not log repeated messages. Repeated errors must occur in same file on same
; line unless ignore_repeated_source is set true.
; http://php.net/ignore-repeated-errors
ignore_repeated_errors = Off

; Ignore source of message when ignoring repeated messages. When this setting
; is On you will not log errors with repeated messages from different files or
; source lines.
; http://php.net/ignore-repeated-source
ignore_repeated_source = Off

; If this parameter is set to Off, then memory leaks will not be shown (on
; stdout or in the log). This has only effect in a debug compile, and if
; error reporting includes E_WARNING in the allowed list
; http://php.net/report-memleaks
report_memleaks = On

; This setting is on by default.
;report_zend_debug = 0

; Store the last error/warning message in $php_errormsg (boolean). Setting this value
; to On can assist in debugging and is appropriate for development servers. It should
; however be disabled on production servers.
; Default Value: Off
; Development Value: On
; Production Value: Off
; http://php.net/track-errors
track_errors = On

; Turn off normal error reporting and emit XML-RPC error XML
; http://php.net/xmlrpc-errors
;xmlrpc_errors = 0

; An XML-RPC faultCode
;xmlrpc_error_number = 0

; When PHP displays or logs an error, it has the capability of inserting html
; links to documentation related to that error. This directive controls whether
; those HTML links appear in error messages or not. For performance and security
; reasons, it's recommended you disable this on production servers.
; Note: This directive is hardcoded to Off for the CLI SAPI
; Default Value: On
; Development Value: On
; Production value: Off
; http://php.net/html-errors
html_errors = On

; If html_errors is set On PHP produces clickable error messages that direct
; to a page describing the error or function causing the error in detail.
; You can download a copy of the PHP manual from http://php.net/docs
; and change docref_root to the base URL of your local copy including the
; leading '/'. You must also specify the file extension being used including
; the dot. PHP's default behavior is to leave these settings empty.
; Note: Never use this feature for production boxes.
; http://php.net/docref-root
; Examples
;docref_root = "/phpmanual/"

; http://php.net/docref-ext
;docref_ext = .html

; String to output before an error message. PHP's default behavior is to leave
; this setting blank.
; http://php.net/error-prepend-string
; Example:
;error_prepend_string = ""

; String to output after an error message. PHP's default behavior is to leave
; this setting blank.
; http://php.net/error-append-string
; Example:
;error_append_string = ""

; Log errors to specified file. PHP's default behavior is to leave this value
; empty.
; http://php.net/error-log
; Example:
;error_log = php_errors.log
error_log =  "C:\xampp\php\logs\php_error_log"
; Log errors to syslog (Event Log on NT, not valid in Windows 95).
;error_log = syslog

inserted by FC2 system