Switch from user 'root' to 'catalyst' on VM
[catagits/Catalyst-Manual.git] / lib / Catalyst / Manual / Tutorial / 07_Debugging.pod
1 =head1 NAME
2
3 Catalyst::Manual::Tutorial::07_Debugging - Catalyst Tutorial - Chapter 7: Debugging
4
5
6 =head1 OVERVIEW
7
8 This is B<Chapter 7 of 10> for the Catalyst tutorial.
9
10 L<Tutorial Overview|Catalyst::Manual::Tutorial>
11
12 =over 4
13
14 =item 1
15
16 L<Introduction|Catalyst::Manual::Tutorial::01_Intro>
17
18 =item 2
19
20 L<Catalyst Basics|Catalyst::Manual::Tutorial::02_CatalystBasics>
21
22 =item 3
23
24 L<More Catalyst Basics|Catalyst::Manual::Tutorial::03_MoreCatalystBasics>
25
26 =item 4
27
28 L<Basic CRUD|Catalyst::Manual::Tutorial::04_BasicCRUD>
29
30 =item 5
31
32 L<Authentication|Catalyst::Manual::Tutorial::05_Authentication>
33
34 =item 6
35
36 L<Authorization|Catalyst::Manual::Tutorial::06_Authorization>
37
38 =item 7
39
40 B<07_Debugging>
41
42 =item 8
43
44 L<Testing|Catalyst::Manual::Tutorial::08_Testing>
45
46 =item 9
47
48 L<Advanced CRUD|Catalyst::Manual::Tutorial::09_AdvancedCRUD>
49
50 =item 10
51
52 L<Appendices|Catalyst::Manual::Tutorial::10_Appendices>
53
54 =back
55
56
57 =head1 DESCRIPTION
58
59 This chapter of the tutorial takes a brief look at the primary options
60 available for troubleshooting Catalyst applications.
61
62 Source code for the tutorial in included in the F</home/catalyst/Final>
63 directory of the Tutorial Virtual machine (one subdirectory per
64 chapter).  There are also instructions for downloading the code in
65 L<Catalyst::Manual::Tutorial::01_Intro>.
66
67
68 Note that when it comes to debugging and troubleshooting, there are two
69 camps:
70
71 =over 4
72
73 =item * 
74
75 Fans of C<log> and C<print> statements embedded in the code.
76
77 =item * 
78
79 Fans of interactive debuggers.
80
81 =back
82
83 Catalyst is able to easily accommodate both styles of debugging.
84
85
86 =head1 LOG STATEMENTS
87
88 Folks in the former group can use Catalyst's C<$c-E<gt>log> facility.
89 (See L<Catalyst::Log> for more detail.) For example, if you add the
90 following code to a controller action method:
91
92     $c->log->info("Starting the foreach loop here");
93     
94     $c->log->debug("Value of \$id is: ".$id);
95
96 Then the Catalyst development server will display your message along
97 with the other debug output. To accomplish the same thing in a TT
98 template view use:
99
100     [% c.log.debug("This is a test log message") %]
101
102 As with many other logging facilities, a method is defined for each of
103 the following "logging levels" (in increasing order of
104 severity/importance):
105
106     $c->log->debug
107     $c->log->info
108     $c->log->warn
109     $c->log->error
110     $c->log->fatal
111
112 You can also use L<Data::Dumper> in both Catalyst code
113 (C<use Data::Dumper; $c-E<gt>log-E<gt>debug("\$var is: ".Dumper($var));)>)
114 and TT templates (C<[% Dumper.dump(book) %]>.
115
116 B<NOTE:> Whether you are a logging fanatic or not, we strongly recommend
117 that you take advantage of L<Log::Log4perl> or L<Log::Dispatch>.  It's
118 easy to use L<Catalyst::Log> with either of these and they will provide
119 a huge amount of extra functionality that you will want in virtually
120 every production application you run or support.
121
122
123 =head1 RUNNING CATALYST UNDER THE PERL DEBUGGER
124
125 Members of the interactive-debugger fan club will also be at home with
126 Catalyst applications.  One approach to this style of Perl debugging is
127 to embed breakpoints in your code.  For example, open
128 C<lib/MyApp/Controller/Books.pm> in your editor and add the
129 C<DB::single=1> line as follows inside the C<list> method (I like to
130 "left-justify" my debug statements so I don't forget to remove them, but
131 you can obviously indent them if you prefer):
132
133     sub list :Local {
134         # Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst
135         # 'Context' that's used to 'glue together' the various components
136         # that make up the application
137         my ($self, $c) = @_;
138     
139     $DB::single=1;
140     
141         # Retrieve all of the book records as book model objects and store in the
142         # stash where they can be accessed by the TT template
143         $c->stash->{books} = [$c->model('DB::Book')->all];
144     
145         # Set the TT template to use.  You will almost always want to do this
146         # in your action methods.
147         $c->stash->{template} = 'books/list.tt2';
148     }
149
150 This causes the Perl Debugger to enter "single step mode" when this
151 command is encountered (it has no effect when Perl is run without the
152 C<-d> flag).
153
154 B<NOTE:> The C<DB> here is the Perl Debugger, not the DB model.
155
156 If you haven't done it already, enable SQL logging as before:
157
158     $ export DBIC_TRACE=1
159
160 To now run the Catalyst development server under the Perl debugger,
161 simply prepend C<perl -d> to the front of C<script/myapp_server.pl>:
162
163     $ perl -d script/myapp_server.pl
164
165 This will start the interactive debugger and produce output similar to:
166
167     $ perl -d script/myapp_server.pl  
168     
169     Loading DB routines from perl5db.pl version 1.3
170     Editor support available.
171     
172     Enter h or `h h' for help, or `man perldebug' for more help.
173     
174     main::(script/myapp_server.pl:16):      my $debug         = 0;
175     
176       DB<1> 
177
178 Press the C<c> key and hit C<Enter> to continue executing the Catalyst
179 development server under the debugger.  Although execution speed will be
180 slightly slower than normal, you should soon see the usual Catalyst
181 startup debug information.
182
183 Now point your browser to L<http://localhost:3000/books/list> and log
184 in.  Once the breakpoint is encountered in the
185 C<MyApp::Controller::list> method, the console session running the
186 development server will drop to the Perl debugger prompt:
187
188     MyApp::Controller::Books::list(/home/catalyst/MyApp/script/../lib/MyApp/Controller/Books.pm:48):
189     48:         $c->stash->{books} = [$c->model('DB::Book')->all];
190     
191       DB<1>
192
193 You now have the full Perl debugger at your disposal.  First use the
194 C<next> feature by typing C<n> to execute the C<all> method on the Book
195 model (C<n> jumps over method/subroutine calls; you can also use C<s> to
196 C<single-step> into methods/subroutines):
197
198       DB<1> n
199     SELECT me.id, me.title, me.rating, me.created, me.updated FROM book me:
200     MyApp::Controller::Books::list(/home/catalyst/MyApp/script/../lib/MyApp/Controller/Books.pm:53):
201     53:         $c->stash->{template} = 'books/list.tt2';
202     
203       DB<1>
204
205 This takes you to the next line of code where the template name is set.
206 Notice that because we enabled C<DBIC_TRACE=1> earlier, SQL debug output
207 also shows up in the development server debug information.
208
209 Next, list the methods available on our C<Book> model:
210
211       DB<1> m $c->model('DB::Book')
212     ()
213     (0+
214     (bool
215     __result_class_accessor
216     __source_handle_accessor
217     _add_alias
218     __bool
219     _build_unique_query
220     _calculate_score
221     _collapse_cond
222     <lines removed for brevity>
223     
224       DB<2>
225
226 We can also play with the model directly:
227
228       DB<2> x ($c->model('DB::Book')->all)[1]->title
229     SELECT me.id, me.title, me.rating, me.created, me.updated FROM book me:
230     0  'TCP/IP Illustrated, Volume 1'
231
232 This uses the Perl debugger C<x> command to display the title of a book.
233
234 Next we inspect the C<books> element of the Catalyst C<stash> (the C<4>
235 argument to the C<x> command limits the depth of the dump to 4 levels):
236
237       DB<3> x 4 $c->stash->{books}
238     0  ARRAY(0xa8f3b7c)
239        0  MyApp::Model::DB::Book=HASH(0xb8e702c)
240           '_column_data' => HASH(0xb8e5e2c)
241              'created' => '2009-05-08 10:19:46'
242              'id' => 1
243              'rating' => 5
244              'title' => 'CCSP SNRS Exam Certification Guide'
245              'updated' => '2009-05-08 10:19:46'
246           '_in_storage' => 1
247     <lines removed for brevity>
248
249 Then enter the C<c> command to continue processing until the next
250 breakpoint is hit (or the application exits):
251
252       DB<4> c
253     SELECT author.id, author.first_name, author.last_name FROM ...
254
255 Finally, press C<Ctrl+C> to break out of the development server.
256 Because we are running inside the Perl debugger, you will drop to the
257 debugger prompt.
258
259     ^CCatalyst::Engine::HTTP::run(/usr/local/share/perl/5.10.0/Catalyst/Engine/HTTP.pm:260):
260     260:            while ( accept( Remote, $daemon ) ) {
261
262     DB<4>
263
264 Finally, press C<q> to exit the debugger and return to your OS shell
265 prompt:
266
267       DB<4> q
268     $
269
270 For more information on using the Perl debugger, please see C<perldebug>
271 and C<perldebtut>.  For those daring souls out there, you can dive down
272 even deeper into the magical depths of this fine debugger by checking
273 out C<perldebguts>.
274
275 You can also type C<h> or C<h h> at the debugger prompt to view the
276 built-in help screens.
277
278 For an excellent book covering all aspects of the Perl debugger, we
279 highly recommend reading 'Pro Perl Debugging' by Richard Foley.
280
281 Oh yeah, before you forget, be sure to remove the C<DB::single=1> line
282 you added above in C<lib/MyApp/Controller/Books.pm>.
283
284 =head1 DEBUGGING MODULES FROM CPAN
285
286 Although the techniques discussed above work well for code you are
287 writing, what if you want to use print/log/warn messages or set
288 breakpoints in code that you have installed from CPAN (or in module that
289 ship with Perl)?  One helpful approach is to place a copy of the module
290 inside the C<lib> directory of your Catalyst project.  When Catalyst
291 loads, it will load from inside your C<lib> directory first, only
292 turning to the global modules if a local copy cannot be found.  You can
293 then make modifications such as adding a C<$DB::single=1> to the local
294 copy of the module without risking the copy in the original location.
295 This can also be a great way to "locally override" bugs in modules while
296 you wait for a fix on CPAN.
297
298 Matt Trout has suggested the following shortcut to create a local copy
299 of an installed module:
300
301     mkdir -p lib/Module; cp `perldoc -l Module::Name` lib/Module/
302
303 Note: If you are following along in Debian 6 or Ubuntu, you will need to
304 install the C<perl-doc> package to use the C<perldoc> command.  Use
305 C<sudo aptitude install perl-doc> to do that.
306
307 For example, you could make a copy of
308 L<Catalyst::Plugin::Authentication> with the following command:
309
310     mkdir -p lib/Catalyst/Plugin; cp \
311         `perldoc -l Catalyst::Plugin::Authentication` lib/Catalyst/Plugin
312
313 You can then use the local copy inside your project to place logging
314 messages and/or breakpoints for further study of that module.
315
316 B<Note:> Matt has also suggested the following tips for Perl debugging:
317
318 =over 4
319
320 =item * 
321
322 Check the version of an installed module:
323
324     perl -M<mod_name> -e 'print "$<mod_name>::VERSION\n"'
325
326 For example:
327
328     $ perl -MCatalyst::Plugin::Authentication -e \
329         'print $Catalyst::Plugin::Authentication::VERSION;'
330     0.07
331
332 and if you are using bash aliases:
333
334     alias pmver="perl -le '\$m = shift; eval qq(require \$m) \
335         or die qq(module \"\$m\" is not installed\\n); \
336         print \$m->VERSION'"
337
338 =item * 
339
340 Check if a modules contains a given method:
341
342     perl -MModule::Name -e 'print Module::Name->can("method");'
343
344 For example:
345
346     $ perl -MCatalyst::Plugin::Authentication -e \
347         'print Catalyst::Plugin::Authentication->can("user");'
348     CODE(0x9c8db2c)
349
350 If the method exists, the Perl C<can> method returns a coderef.
351 Otherwise, it returns undef and nothing will be printed.
352
353 =back
354
355
356 =head1 TT DEBUGGING
357
358 If you run into issues during the rendering of your template, it might
359 be helpful to enable TT C<DEBUG> options.  You can do this in a Catalyst
360 environment by adding a C<DEBUG> line to the C<__PACKAGE__->config>
361 declaration in C<lib/MyApp/View/HTML.pm>:
362
363     __PACKAGE__->config({
364         TEMPLATE_EXTENSION => '.tt2',
365         DEBUG              => 'undef',
366     });
367
368 There are a variety of options you can use, such as 'undef', 'all',
369 'service', 'context', 'parser' and 'provider'.  See
370 L<Template::Constants> for more information (remove the C<DEBUG_>
371 portion of the name shown in the TT docs and convert to lower case for
372 use inside Catalyst).
373
374 B<NOTE:> B<Please be sure to disable TT debug options before continuing
375 with the tutorial> (especially the 'undef' option -- leaving this
376 enabled will conflict with several of the conventions used by this
377 tutorial to leave some variables undefined on purpose).
378
379 Happy debugging.
380
381
382 You can jump to the next chapter of the tutorial here:
383 L<Testing|Catalyst::Manual::Tutorial::08_Testing>
384
385
386 =head1 AUTHOR
387
388 Kennedy Clark, C<hkclark@gmail.com>
389
390 Feel free to contact the author for any errors or suggestions, but the
391 best way to report issues is via the CPAN RT Bug system at
392 L<https://rt.cpan.org/Public/Dist/Display.html?Name=Catalyst-Manual>.
393
394 Copyright 2006-2011, Kennedy Clark, under the
395 Creative Commons Attribution Share-Alike License Version 3.0
396 (L<http://creativecommons.org/licenses/by-sa/3.0/us/>).