9780596521424
appendix_id64266.html

Chapter 16. Appendix

Configuration

Configuration

Environments

Action Mailer Configuration

Active Support Cache Store

config.cache_store

Rails Initializers

Logging

Logging provides a way to record messages from a running application. The messages can be used for debugging or analysis at a later time. Rails produces very verbose, informative, colored logs with each request. Each component of Rails is configured with a logger during initialization.

All of the most commonly used classes in Rails provide access to a logger logger accessor for convenient access to the logger. This includes Active Record models, controllers, views, and Active Resource models. The logger accessor returns the currently configured logger for the class.

The logger has a method for each of the log levels. Adding a message to the log is as simple as calling the method for the log level you want the message to be logged at. The following code logs a message at the :info log level:

logger.info "Successful login for #{@user.name}"

Whether or not a particular message is logged by the logger depends on the log level. If the severity of the message being logged is less than the current log level then the message is ignored. The logging severities supported by Rails compatible loggers can be seen in Table 16.1, “Logging severities”.

Table 16.1. Logging severities

NameSeverity
:debug0
:info1
:warn2
:error3
:fatal4
:unknown5

By default, the Rails test and development environments log with a level of :debug. The Rails production environment uses a default log level of :info. The logger will not log messages logged at a level lower than its current log level. This means that the development environment will log all messages, whereas the production environment will ignore all log messages at a log level lower than :info. This allows you to place different logging statements throughout your code with different log levels.

The easiest way to debug these problems is to monitor the log files. An easy way to monitor your logs is to use the Unix or Linux tail command. Execute the following from your project's root directory to have tail monitor the log file.

$ tail -f log/development.log

The -f flag tells tail to output appended data as the file grows.

Configuration

Loggers are very simple to setup, and if you are using the default Rails configuration then you don't need to worry about configuring a logger at all. The default logger used by Rails is the ActiveSupport::BufferedLogger. The buffered logger is good in a production environment because log messages are not immediately flushed to the disk. Logs are buffered in memory and then flushed at the end of the request or when the buffer is full, which helps reduce disk I/O in a production environment. You can configure logger other than the default by setting config.logger in the

The logger logs to a file in the log folder of your application named after the environment you run your application in. For example, an application running in the development environment logs to a file named log/development.log. The log file should be the first place you look when you are investigating any odd behavior of your application.

Rails is compatible with the Ruby Logger class, the Log4r::Logger, the SyslogLogger, and any other logger implementing a similar, compatible interface.

There are three settings pertaining to the logger in the configuration file for your environment:

logger

The logger to use for logging in all configured frameworks. Defaults to ActiveSupport::BufferedLogger.

log_level

The log level to set the logger at. Defaults to :info in the production environment and :debug in any other environment.

log_path

The destination file for log messages. Defaults to log/#{environment}.log where environment is the current Rails environment, such as development.

HTTP Status Codes

HTTP Status Code Mapping

Table 16.2. 1xx Informational

CodeSymbolPhrase
100:continueContinue
101:switching_protocolsSwitching Protocols
102:processingProcessing

Table 16.3. 2xx Success

CodeSymbolPhrase
200:okOK
201:createdCreated
202:acceptedAccepted
203:non_authoritative_informationNon-Authoritative Information
204:no_contentNo Content
205:reset_contentReset Content
206:partial_contentPartial Content
207:multi_statusMulti-Status
226:im_usedIM Used

Table 16.4. 3xx Redirection

CodeSymbolPhrase
300:multiple_choicesMultiple Choices
301:moved_permanentlyMoved Permanently
302:foundFound
303:see_otherSee Other
304:not_modifiedNot Modified
305:use_proxyUse Proxy
306:reservedReserved
307:temporary_redirectTemporary Redirect

Table 16.5. 4xx Client Error

CodeSymbolPhrase
400:bad_requestBad Request
401:unauthorizedUnauthorized
402:payment_requiredPayment Required
403:forbiddenForbidden
404:not_foundNot Found
405:method_not_allowedMethod Not Allowed
406:not_acceptableNot Acceptable
407:proxy_authentication_requiredProxy Authentication Required
408:request_timeoutRequest Timeout
409:conflictConflict
410:goneGone
411:length_requiredLength Required
412:precondition_failedPrecondition Failed
413:request_entity_too_largeRequest Entity Too Large
414:request_uri_too_longRequest-URI Too Long
415:unsupported_media_typeUnsupported Media Type
416:requested_range_not_satisfiableRequested Range Not Satisfiable
417:expectation_failedExpectation Failed
422:unprocessable_entityUnprocessable Entity
423:lockedLocked
424:failed_dependencyFailed Dependency
426:upgrade_requiredUpgrade Required

Table 16.6. 5xx Server Error

CodeSymbolPhrase
500:internal_server_errorInternal Server Error
501:not_implementedNot Implemented
502:bad_gatewayBad Gateway
503:service_unavailableService Unavailable
504:gateway_timeoutGateway Timeout
505:http_version_not_supportedHTTP Version Not Supported
506:variant_also_negotiatesVariant Also Negotiates
507:insufficient_storageInsufficient Storage
510:not_extendedNot Extended

Memcached

Memcached is a distributed memory object caching system.

Installing Memcached

Mac OS X Leopard

MacPorts is required to install Memcached on Mac OS X Leopard. Information about installing MacPorts can be found at http://www.macports.org.

The first step is to install the Memcached server:

$ sudo port install memcached

MacPorts installs Memcached and creates a startup item for it automatically, but the startup item is disabled by default. To enable Memcached to start at startup run:

$ sudo launchctl load -w /Library/LaunchDaemons/org.macports.memcached.plist

Memcached will now be running on your system and will start itself automatically at startup. By default it will be run with 64 MB of RAM on port 11211. You can change the settings by modifying the file /opt/local/etc/LaunchDaemons/org.macports.memcached.

To test that your Memcached installation was successful you can connect to it with Telnet. Telnet to port 11211 on localhost where Memcached is running and send the stats command. The output should be similar to the following:

$ telnet localhost 11211
Trying ::1...
Connected to localhost.
Escape character is '^]'.
stats
STAT pid 527
STAT uptime 441
STAT time 1230761183
STAT version 1.2.6
STAT pointer_size 32
STAT rusage_user 0.006001
STAT rusage_system 0.012105
STAT curr_items 0
STAT total_items 0
STAT bytes 0
STAT curr_connections 6
STAT total_connections 9
STAT connection_structures 7
STAT cmd_get 0
STAT cmd_set 0
STAT get_hits 0
STAT get_misses 0
STAT evictions 0
STAT bytes_read 57
STAT bytes_written 942
STAT limit_maxbytes 67108864
STAT threads 4
END
quit
Connection closed by foreign host.

Now that you've verified that memcached is running it can be used in your Rails application. Rails bundles a Ruby memcache client into Active Support, so there is nothing further to install. Rails will automatically use a newer version of memcache-client from RubyGems if present.

Site last updated on: December 11, 2012 at 10:21:28 PM PST
Cover for Rails 3 in a Nutshell

View 2 comments

  1. john – Posted Sept. 1, 2009

    Testing, testing...

  2. noneofthat – Posted March 8, 2010

    and how did that work out for you?

Add a comment

View 2 comments

  1. Special_Dragonfly – Posted Dec. 9, 2009

    Duplicate information with the line directly above. Above: "The simplest way to monitor the log file of a running application is to use the Unix tail command."

    This paragraph: "An easy way to monitor your logs is to use the Unix or Linux tail command."

    Suggestion: Remove the line above

  2. codyfauser – Posted Jan. 8, 2010

    Fixed, thanks

Add a comment

View 1 comment

  1. pascal – Posted Feb. 3, 2010

    We're working with this tech now, and it's great. This is just an internal comment test.

Add a comment