4elements, Amsterdam, Holland

  1. Subsequent costing.

    I think that every Freelancer or Web Design Company experienced the following story.  The story is what happened to me and since than I provide my potential  new clients with a custom made checklist.

    A potential new client calls me and we made an appointment to meet. With my up-to-date portfolio I went to the client and the meeting went great, I asked the right questions and if needed explained my questions to them.

    Back at the office it was time to write my quotation, I always start writhing my quotation the same day while I don’t like to keep a client waiting too longs. It took me two days, it’s a big assignment and all needed to be perfect.

    Next the design. A complex website, member section, payment options and so on. It took me 5 days to finish 3 Photoshop pages of the new website. I always design 3 pages and include it in the quotation, if they sign the quotation I’ll design the rest.

    Quotation and design where handed over within the agreed timeframe, 2 weeks, and we walked through the quote and design. The Client loved it, the quote was okay, within their budget and they ask if it was possible to respond within 2 weeks, of course I agreed. Especially while it was a big project, the quote was over $20.000. After the 2 weeks we met again, they had some changes to the website and I re-wrote the quote. This continued several times, ending up with a quote of $25.000 and ready to roll.

    I remember it clearly, it was on a sunny Wednesday morning, the day my potential new client would become my client and sign. So I went over as promised and than it hit me.

    Client: “Well, we’re sorry to tell you but we found an other company that could do the same for just $1.000”

    I was speechless!

    Whatever I tried, lowering my quotation to $1.000 was absolutely not reasonable or possible, the client made his decision. So after several weeks, maybe months, hard work for this potential new client ended in loosing the client.

    6+ months later I spoke with the client just to see how everything was going, I knew when their deadline was. Website was still not done and won’t be, “Why” Was my question? Well, the company, that took my new client, didn’t mention that the $1.000 was a kind of start fee and that all other work would be Subsequent costing. $50.000 later the website was half finished and absolutely not ready for any, near future, launch.

    Final words of the, lost, client where: “We had to go with you, than we would never had this problem”, he was right…

    The point I want to make with this story.

    As client: always ask if the total price is a fixed price, without Subsequent costing. (Until some point of course, while some non calculated extra adjustments will have their price. Use an extra quote for that to be safe.)

    ​Attached to this blog, a checklist for clients who are ready for a new website or website re-design. What information do you need to know and have before talking to a web designer / company / freelancer.

    Download checklist
    We share this article with our sister company, designscan.me, get insight in your website



    Leave a comment › Posted in: Daily

    1. Build a Custom WordPress User Flow — Part 1: Replace the Login Page

      Thanks to its nearly endless customizability through plugins and themes, WordPress has come a long way from its roots as a blogging platform, today acting as the backbone for all kinds of web based applications from online stores to membership sites and e-book authoring platforms.

      While traditionally only the site admins would log in to the WordPress dashboard, many of these new, application-like uses change that: when users need to be authenticated, the WordPress login is extended to visitors and customers. 

      WordPress provides good tools for managing user roles and capabilities, and they can be further extended with the help of  plugins, but for a professional touch, that's not quite enough — you also need to make sure the user experience fits that of your product as a whole. After all, seeing the default (or lightly styled) WordPress login screen when logging in to a web based application can leave an unfinished impression.

      In this three-part tutorial series, I will show you how to fix this by customizing the login and new user registration functionality to fit your site's looks, without violating WordPress's best practices.

      What You Will Learn in This Tutorial

      By default, WordPress uses a good looking, but generic login screen that we are all very familiar with:

      WordPress login screen

      The screen does it job, and it doesn't look bad at all. But when building a serious web site, you don't keep the default theme, so why would you keep the default login?

      It is possible to do some styling using CSS and a number of actions and filters provided by the login page itself. But while these changes can lead to decent results, I think the approach still has its shortcomings, most importantly the fact that the login page is totally separate from the rest of your site.

      That's why, today, we are not going to settle with the simple, cosmetic changes but will instead build a login page of our own. One that feels like a part of the WordPress based web site rather than something added on top of it.

      To do this, in this tutorial, we will build a WordPress plugin that replaces the login page with a combination of a custom WordPress page and a shortcode used for rendering the login form. While doing so, you will learn about the WordPress login flow, the points were we can hook into it and modify it to our needs, as well as developing WordPress plugins. 

      Then, in the next two tutorials in the series, we will continue from there, customizing the new user registration and password reset functionality in the same way.

      You can follow the tutorial implementing your own plugin as you go, or you can download the full sample code from the linked GitHub repository.

      Let’s get started!

      Create the Plugin

      While some of the customization is clearly dependent on the theme used, the functionality of making the login page customizable itself is very much independent of themes and therefore best implemented as a plugin.

      So, the first thing as we get started is to create a plugin to hold all of the customizations we will build in this tutorial.   

      First, create a directory to hold the plugin, naming it personalize-login. Then, inside that directory, create another directory and name it templates. In this directory, we will add the templates used for rendering the different HTML forms created in this series (we'll get back to this later in the tutorial).

      Then, with the directories created, place a PHP file called personalize-login.php in the plugin directory. This file will contain all the code for this plugin, starting with the plugin initialization:

      The plugin's constructor is still empty, but not for long: we'll soon start adding content to it, in the form of filter and action hooks.

      But first, let's create some WordPress pages.

      Create the Custom Pages For Login

      By default, when you try to access the WordPress admin, or click on a Log In link on your WordPress site (assuming your theme displays one), WordPress sends you to wp-login.php, the default version of the WordPress login page. Now, we'll change that and send the user to a custom WordPress page. 

      To do this, first we need to create a page.

      At a later point, it might make sense to add a settings screen for picking the pages to use for each of the different steps in the user management flow. For now, however, I want to keep your focus on the customization and not confuse you with creating settings pages, so we will go with the simple option and just create the pages automatically when the plugin is activated.

      In a WordPress plugin, the way to do this is by registering a static function to a plugin activation hook so that it is called when plugin is activated through the Plugins menu. 

      Notice that the activation hook does not get called when a plugin is updated through the plugin updates. So, if you make changes to the code inside the activation hook and want to have them take action, make sure that you deactivate and activate the plugin manually. 

      To register the activation hook, add the following piece of code at the end of your plugin file:

      Then, inside the plugin class, add the static function plugin_activated:

      The plugin activation function creates a set of pages using the data from the $page_definitions array defined on lines 8-17. Using this array, we can easily add more pages (as we'll do in the next parts of the series) without copying and pasting page creation code. All we'll need to do is to add a new item to the array, using the page slug (permalink) as the key and an array containing the page's title and initial content as value. 

      In the code snippet above, I added two pages: one for the login page (member-login) and one for an account page where we'll direct the logged in non-admin users (member-account).

      On lines 19-36, you'll find the actual page creation code. The function loops through the array of page definitions checking if a page with the given slug exists already and creating a page if it doesn't. 

      Creating the pages is done using the WordPress function wp_insert_post. For more information on its parameters, you can check the WordPress Codex.

      Now, let's activate the plugin and see that pages are created the way they should. Go to your WordPress admin dashboard and activate the plugin.Then, when you access the Pages menu, you should see both new pages in place:

      The Pages list now shows the two pages we just created

      If you click over to view the Sign In page, you'll find an almost blank page with nothing but a title and our shortcode. 

      But it won't be blank for long.

      Add Content to the Login Page

      With the first two pages in place, we can start adding content to them.

      In this first tutorial, we will build the Log In — or Sign In (see this article on login best practices for a discussion on what words to use) — page. Then, in the next two tutorials, we will continue from there, building the "Register" and "Forgot Your Password" pages.

      Having your own page for the login screen gives you many options for customizing its looks and content. On the easier side, you can use the WordPress page editor to add text and graphics (e.g. Instructions for the user, or maybe an advertisement about the benefits of registering an account). At the other extreme, you could even create your own page template and write the HTML for the page from scratch. 

      In this tutorial, we will do something from the middle and build a shortcode that will display a login form on the login page. If you later decide to create your own page template, you can always call this shortcode from your theme's code.

      Step 1: Create the Shortcode

      As you remember from the page creation step, we already added a shortcode (custom-login-form) in the body of the login page when we created it in the plugin activation hook. However, as we haven't yet built a handler for that shortcode, WordPress now renders it as regular text.

      Let's create the handler now. In your plugin class's constructor, add the following shortcode definition:

      This line registers a function inside the plugin class, render_login_form, for rendering the shortcode custom-login-form

      To make this work, add the function:

      First, on lines 10-13, the function reads in the shortcode parameters — currently there is just one, show_title, which take a boolean value. If the parameter is omitted, by default, it is set to false.

      Then, the shortcode function checks if the user is logged in, rendering the form only for users who are not yet logged in.

      On lines 19-25, the function checks if a redirect_to request variable was passed to the login page. This parameter is what gets you to the correct WordPress admin page after login, so it's important to not forget it as we customize the login flow. If no redirect_to is set, or the URL is not valid, the function uses the current page's permalink instead.

      To keep presentation separate from functionality, the rendering is done using a template placed in the templates directory you created at the beginning of this tutorial.

      As we already know we will be adding more templates later in this series (for example the new user registration form), we will prepare for this and separate the template rendering into its own function to avoid duplicating code (lines 27-28). Variables needed in rendering the template are passed as an associative array, $attributes.

      Add the function, get_template_html, to the plugin class:

      The function looks for the given template in the templates directory and renders it into a string using an output buffer (lines 14-23). The output buffer collects everything that is printed between ob_start and ob_end_clean so that it can then be retrieved as a string using ob_get_contents

      At the end of the function, the shortcode output is returned for rendering on the page (as you saw in the previous snippet, the shortcode function then returns it to WordPress for rendering).

      The do_action function calls surrounding the require are optional but show a handy way to give other developers a chance to add further customizations before and after the template is rendered.

      To complete the shortcode, you still need to create the HTML template: Create a PHP file in your templates directory, naming it login_form.php. Inside the template, to test, just add the text Sign In. Now, when you navigate to your custom login page, you'll see something like this (using the current WordPress default theme, Twenty Fifteen):

      The new Sign In page still empty

      Your shortcode is working, but it's still missing the login form. Let's add that now.

      Step 2: Add Contents to the HTML Template

      Continuing the work on login_form.php, remove the placeholder text and replace it with the following content that will show a fully functional WordPress login form:

      First, the template begins with an optional title, controlled by the shortcode parameter, show_title as explained earlier.

      Then, on lines 6-14, you'll notice that most of the rendering of the login form is still done by WordPress, using the function wp_login_form. The function takes an optional parameter array that can be used to customize the contents of the login form. 

      Here are the customizations I have made in our example code:

      • First, I wanted to use the wording "Sign In" instead of the default "Log In".  
      • Second, I wanted to use use email addresses as user names, so I changed the label for user name to "Email".
      • Third, there is the redirect URL which was forwarded through the shortcode handler function above.

      For further customizations, here's the full list of parameters you can use in the parameter array passed to wp_login_form:

      Default Value
      Whether the login form should be rendered. If false, the output is returned as a string.
      The URL to redirect to after successful login.Redirects back to current page.
      The HTML id of the login form.
      The text label for the user name field.
      __( 'Username' )
      The text label for the password field.
      __( 'Password' )
      The text label for the "Remember Me" checkbox.
      __( 'Remember Me' )
      The text label for the "Log In" button.
      __( 'Log In' )
      The HTML id for the user name field.
      The HTML id for the password field.
      The HTML id for the "Remember Me" checkbox.
      The HTML id for the submit button.wp-submit
      Whether the "Remember Me" checkbox should be shown or not.true
      Default value for user name.Empty
      Whether the "Remember Me" checkbox should be checked initially or not.false

      Finally, on lines 16-18, there is a link to the WordPress lost password functionality — which we will replace with our own version in Part 3 of the tutorial series.

      Now, the login page looks like this: 

      Custom login form

      For most uses, this will be enough customization, but if you want to go deeper, there is nothing stopping you from creating the login form from scratch. 

      In this case, you can just create a HTML form and post its content to  wp-login.php — the full login URL for your current site is returned by the WordPress function wp_login_url. The form needs to have the fields log and pwd for the login and password respectively.

      Here's how you would create a login form that looks (and functions) just like the one above — without using wp_login_form:

      WordPress handles the login functionality, so the login form is already fully functional: Enter your valid user name and password and hit Sign In and you will be logged in just fine.

      It's when you enter invalid data that you'll notice everything isn't quite ready yet: Instead of being redirected back to the login page we just created, you will see the regular WordPress login page. Also, unless the user points her browser directly to this newly created login page, she still sees the default WordPress login.

      We need to take the new login page to use by redirecting users to it.

      Redirect the Visitor to Login Page

      Let's start with bringing the user to the login page in the first place.

      Step 1: Redirect the User to Our Login Page

      When a user tries to access any page inside the WordPress admin, or clicks on a Log in link in the Meta widget, he is sent to wp-login.php. Next, we want to change this functionality and point the user to our own member-login page instead.

      All of the WordPress functionality we are customizing in this series from login to password resetting is handled in wp-login.php with the different parts of the functionality identified with a parameter called action

      If you look at the code inside the PHP file, you will notice that right before the actual login functionality begins, two actions are fired: login_init and login_form_{action} where {action} is the name of an action being executed (for example login, postpass, or logout).

      The second one is more specific, so by using it, we won't have to do all that much checking ourselves: just by hooking a function to login_form_login, we can target our redirect functionality precisely to the moment a user enters the login page.

      Add the following action to the plugin class's constructor:

      Then, add the action function:

      The redirect_to_custom_login function is called in two situations: first, when the user enters the login page, and second, when he or she submits the login form. To differentiate between the two, we look at the request method: the form is submitted using POST while the page is loaded using GET

      So, to let wp-login.php handle the actual login and authentication, on line 5, we make sure that the redirect is only done on GET requests.

      On line 6, if a request variable redirect_to is passed in, we'll store it in a temporary variable $redirect_to.

      Already logged in users don't need to go through the login form, so we'll redirect them to either to the WordPress dashboard or the member-account page created earlier (lines 8-11). To prepare for similar redirects in the rest of the tutorial series, we'll separate the redirect to its own function, redirect_logged_in_user, which we'll add soon.

      One thing worth noting is that we are relying on the page slugs (pretty permalinks) in specifying the pages we redirect the user to. If you want to improve this example and make the plugin more flexible, you could look up the pages using the slug and then create permalinks using that data. For now, just turn on pretty permalinks (any option except the default is OK) on the Permalinks settings page and everything will work just fine.

      On lines 15-17, we add the redirect_to parameter to the new request if one is present so that no information is lost at this redirect.

      On line 20, you'll notice that we end the execution rather abruptly using an exit command. This is important because otherwise, the execution will continue with the rest of the action in wp-login.php, maybe causing problems with our customization. Keep an eye on this also in other redirects we do in the rest of the tutorial.

      Now, add the function, redirect_logged_in_user mentioned above:

      The function redirects the user to a different URL depending on his or her access level. For admin users, we also check the $redirect_to parameter: if one is set, the user is directed to this URL instead of the default admin_url.

      Step 2: Redirect When There Are Errors

      We have now covered the first redirect and so, whenever the user first clicks on a link to wp-login.php or tries to access the admin dashboard, he or she is sent to our new login page. But we're not done yet: when there are errors in the login (invalid username or password, empty form, and so on) the user still sees the default login page. 

      In WordPress, user authentication happens through a function called wp_authenticate —  located in pluggable.php if you want to take a look. 

      The function does some basic sanitization of parameters and then calls the filters attached to the filter hook authenticate. This is to allow plugins to replace the authentication flow with their own functionality, but most importantly for us, even the WordPress default authentication is done through this filter

      At this point, we are not interested in replacing the authentication, but the filter hook is still useful as it gives us a chance to collect the errors from other filters and proceed accordingly: 

      1. Hook a new function to the authenticate filter using a high enough priority (in WordPress filters and actions, a higher number in the priority parameter means that the function will be called later in the filter processing order).
      2. The filter function will receive the results from previous filters in the filter chain as a parameter. Use this data to check if there were any errors in the login.
      3. If no errors are found, let everything proceed normally so WordPress can finish the login. 
      4. If there are errors, instead of letting WordPress do its regular error handling, redirect to our custom login page.

      In the current WordPress version (4.2 at the time of writing), WordPress has the following two filters hooked to authenticate:

      The basic authentication has priority 20 and the priority for wp_authenticate_spam_check is 99, so if we set ours at higher than 99 (I picked 101), it will be run after both of these. It is of course possible that another plugin you use adds a filter with a higher priority, in which case you’ll need to increase the number to take that plugin's errors into account. 

      First, add the new filter definition in our plugin class's constructor:

      Then, add the function, maybe_redirect_at_authenticate, at the end of the plugin class:

      The authenticate filter functions take three parameters: 

      • $user is the signed in user's user object, or an instance of the Wp_Error class if there have been errors in the filter chain so far. 
      • $username is the user name entered by the user trying to log in.
      • $password is the password entered by the user.

      For our use, the first parameter is the interesting one: if $user is an error that means one of the earlier authenticate filter functions has found an error in the login. That's when our  function jumps in (on line 13) to collect all of the error codes and append them to the redirect URL on lines 15-18. Finally, the function redirects the user to our custom login page to display the errors.

      Step 3: Render Error Messages

      The plugin is now catching the errors and redirecting the user back to our custom login page also when it finds some. To make the experience useful for the user, we still need to print out the error messages. 

      First, in our shortcode function, we will use the login parameter sent by the redirect created in the previous step to see what errors have occurred and to replace the error codes with readable error messages. This is a good place to use your imagination and create some fun and personal (but hopefully not annoying) error messages. 

      Create a function for converting error codes to error messages, using a simple switch...case construct. The error codes are the ones used by the WordPress login functionality.

      Then, to use the error messages, add the following code to render_login_form, right before rendering the login form template. It will go through the list of error codes and collect matching error messages into an array, $errors:

      The actual rendering of the error messages is done in the login_form.php template. Add the following right after the login form's title and before the login form:

      Now, the error messages are in place and we can test them. Try signing in using incorrect information and you will be redirected back to our custom page with a custom error message of our own:

      Error message on the custom Sign In page

      Step 4: Show Correct Message at Logout

      We're almost done — but not quite. There are still two more things to do before we can call it for a day and say we have replaced all of the WordPress login flow with our own version: rendering the correct message when a user signs out, and redirecting the user to the correct page after a successful login. 

      Let's start with the logout. 

      Once the user has been logged out from your site, in the function wp_logout, WordPress fires the action wp_logout. This is a good place to hook to and do our own redirects before WordPress redirects the user back to wp-login.php.

      In the plugin class's constructor, add the following line:

      Then add the matching function:

      The function redirects the user to our member-login page with the parameter logged_out appended to the request and then stops the execution.

      Next, modify the login form shortcode function to take this parameter into account. A good place for this code is right after the error message handling we created above:

      Finally, we need to print a notification in the template. Again, add this right after printing out potential errors:

      That's it. Now when you sign in and then sign out, you'll see something like this:

      Sign In page with You have signed out message

      Redirect the User to the Account Page When Logged In

      We have now implemented the custom login and handled all of the error cases. As a final touch, to make everything feel just right, let's add one last redirect. This one will make sure the user always ends up where he or she wants (and is allowed) to go. 

      For admins, this is the admin dashboard and for regular, non-admin users, the (currently empty) member-account page.

      As WordPress provides a filter for returning the redirect URL after a successful login, this one is rather straightforward: all we need to do is to create a function that checks the current user's capabilities and returns the correct redirect URL accordingly.

      To do this, add one last filter, again in the plugin's constructor:

      Then add the matching filter function:

      First, the function checks if the user really was logged in (on line 13) and redirects back to the site's home page if no user is found.

      Then, it picks the correct redirect depending on the current user's capabilities:

      • Admins (checked on line 17, using the user_can function) are redirected to the WordPress admin dashboard (line 20) unless a redirect_to parameter was passed with the request. 
      • Regular users are always redirected to the member-account page to prevent them from accessing the WordPress dashboard. This is of course up to you: if you want, you can for example point them to their user page in the WordPress admin.

      If you like, you can also add more fine grained redirects depending on users' roles and capabilities.

      What’s next?

      That's it. You have now built a plugin to replace the WordPress login screen with a custom page that you can customize to make it fit your theme, or the product you are building on top of WordPress.

      In the next tutorial in this series we will build upon this and create a new user registration flow, adding a few new fields and a captcha to prevent bots from registering. 

      Until then, have fun tweaking your login page!



      Leave a comment › Posted in: Daily

    1. Create a Custom API in Magento: Part Two

      In this series, we're discussing custom APIs in Magento. 

      In the first part, we created a full-fledged custom module to implement the custom API, in which we created the required files to plug in the custom APIs provided by our module. 

      In this second and last part, we'll go through the back-­end section to demonstrate how to consume the APIs.

      Quick Recap

      Let's have a quick recap of the first part. Here's the list of files we've already created:

      • app/etc/modules/Envato_All.xml: It's a file used to enable our custom module.
      • app/code/local/Envato/Customapimodule/etc/config.xml: It's a module configuration file.
      • app/code/local/Envato/Customapimodule/etc/api.xml: It's a file which declares the APIs provided by our module.
      • app/code/local/Envato/Customapimodule/etc/wsdl.xml: In this file, we'll define the API methods as per the convention of WSDL.
      • app/code/local/Envato/Customapimodule/Helper/Data.php: It's a file used by the Magento translation system.
      • app/code/local/Envato/Customapimodule/Model/Product/Api.php: It's a model file which implements the logic for our API methods.
      • app/code/local/Envato/Customapimodule/Model/Product/Api/V2.php: It's a file to support Magento's v2 API.

      Also, if you've already enabled our custom module, you should see that our API method "customapimoduleProductList" is listed along with the other APIs when you visit the http://yourmagentostore/api/v2_soap?wsdl=1 page which lists all available APIs in Magento.

      Magento supports "API Roles" and "API Users". We need "API Roles" since you don't want to allow the user access to each and every API of Magento. The "API Roles" are used to create roles with limited access permissions to the API resources. 

      For example, you could create a role which only allows read-only access to the "Product Listing" APIs. On the other hand, you could create a role which allows catalog modification, and it'll be only assigned to the "authorized" users only!

      Set Up "API User" and "API Role" From the Back­-End

      In this section, we'll create a demo "API Role" and "API User". Later on, we'll use these to consume the custom APIs provided by our module. Head over to the Magento back­-end!

      Set Up an API Role

      Go to System > Web Services > (SOAP/XML­RPC) Roles. Click on Add New Role to create a new role. Under the Role Info tab, I've entered "Demo SOAP Role" in the Role Name field.

      Add New Role - Role Info

      Next, under the Role Resources tab, you'll see the different resources with check boxes. Click on the Products > Product data check-box. It means that "Demo SOAP Role" can only access the "Product data" resource APIs. Click on the Save Role button to save the role information.

      Add New Role - Resources

      Set Up an API User

      Now, let's create the API user and assign the "Demo SOAP Role" to that user. Go to System > Web Services > (SOAP/XML­RPC) Users. Click on Add New User to create a new user. Under the User Info tab, please fill in the required information.

      Add New User - User Info

      Further, under the User Role tab select the Demo SOAP Role radio button. Click on the Save User button to save the user information.

      Add New User - User Role

      So that's it—we've set up the required role and user to access the Magento APIs!

      How to Consume the Magento API

      In this section, we'll see how to call the Magento APIs. Under your document root, create an example PHP file and fill it with the following contents.

      Change "http://www.yourmagentostore.com" to your Magento store URL. As I mentioned earlier, Magento supports two versions of the APIs, v1 and v2. In this example, I've demonstrated both the ways.

      In v2 API mode, first we create a new instance of the "SoapClient" class. Next, we call the "login" method to log in to the Magento store—of course we'll need to provide the username and password of the "API User" created in the earlier section. Finally, we call the "customapimoduleProductList" method to retrieve the list of products! The $session variable is passed as an input parameter to the method to claim the authenticity of the method. An important thing to note here is that "customapimoduleProduct" is the resource prefix and "list" is the method name.

      In v1 API mode, the only different part is the calling of the API method. We are using a generic "call" method, in which a "method name" and other parameters are passed as arguments. As you can see, the "product" is used as a resource prefix and "list" is the method name!


      So that sums up the series! Now you should feel comfortable with the Magento APIs, and you can create custom APIs as per your requirements! Feel free to shoot your suggestions and feedback!



      Leave a comment › Posted in: Daily

    1. The Tuts+ Guide to Template Tags: Fourth Batch

      In the fourth part of the series, we went through the third batch of WordPress template tags. In this fifth part, we're going to go through the fourth batch of the almost 200 template tags. Throughout the tutorial, we'll see template tags about comments again, just like the previous batch.

      Getting & Displaying a Link to the "Comments" Section: get_comments_link() & comments_link()

      These template tags return and display the link to the post's "Comments" section.


      comments_link() doesn't accept any parameters, but get_comments_link() accepts one:

      • $post_ID (optional—integer or object):
        The ID of the post.
        (Default: Current post)


      Getting & Displaying the List of Comments: wp_list_comments()

      This popular template tag lists comments submitted on a post.


      This template tag accepts two parameters:

      • $args (optional—array):
        An array of the following arguments:
        • 'walker' (object): Instance of a Walker class to list comments.
          (Default: NULL)
        • 'max_depth' (integer): The maximum comments depth.
          (Default: Empty)
        • 'style' (string): The style of list ordering ('ul' or 'ol').
          (Default: 'ul')
        • 'callback' (string): Callback function to use.
          (Default: NULL)
        • 'end-callback' (string): Callback function to use at the end.
          (Default: NULL)
        • 'type' (string): Type of comments to list ('all, 'comment', 'pingback', 'trackback' or 'pings').
          (Default: 'all')
        • 'page' (integer): Page ID to list comments for.
          (Default: Empty)
        • 'per_page' (integer): Number of comments to list per page.
          (Default: Empty)
        • 'avatar_size' (integer): Dimensions of avatar pictures.
          (Default: 32)
        • 'reverse_top_level' (string): Ordering of the listed comments ('desc' or 'asc').
          (Default: NULL)
        • 'reverse_children' (boolean): Whether to reverse child comments in the list.
          (Default: Empty)
        • 'format' (string): How to format the comments list.
          (Default: 'html5' if the theme supports HTML5 markup, else 'xhtml')
        • 'short_ping' (boolean): Whether to output short pings.
          (Default: FALSE)
        • 'echo' (boolean): Whether to echo the output (TRUE) or return it (FALSE).
          (Default: TRUE)
      • $comments (optional—array):
        Array of comment objects.
        (Default: All comments for the current post)


      Getting & Displaying the Number of Comments: get_comments_number() & comments_number()

      These template tags get and display how many comments are posted to the post.


      get_comments_number() accepts only one parameter:

      • $post_ID (optional—integer or object):
        The ID of the post.
        (Default: Current post)

      And comments_number() accepts three parameters:

      • $zero (optional—string):
        Text to display if there are no comments.
        (Default: 'No Comments')
      • $one (optional—string):
        Text to display if there is only one comment.
        (Default: '1 Comment')
      • $more (optional—string):
        Text to display if there is more than one comment.
        (Default: '% Comments')


      Getting & Displaying Automatic Classes for Each Comment: get_comment_class() & comment_class()

      These template tags let you add generated semantic classes to wherever you want in the comment loop.


      get_comment_class() accepts three parameters:

      • $class (optional—string or array):
        Extra class names to add.
        (Default: Empty)
      • $comment_ID (optional—integer):
        The ID of the comment to work with.
        (Default: Current comment's ID)
      • $post_ID (optional—integer or object):
        The ID of the post.
        (Default: Current post)

      And comment_class() accepts four parameters:

      • $class (optional—string or array):
        Extra class names to add.
        (Default: Empty)
      • $comment_ID (optional—integer):
        The ID of the comment to work with.
        (Default: Current comment's ID)
      • $post_ID (optional—integer or object):
        The ID of the post.
        (Default: Current post)
      • $echo (optional—boolean):
        Whether echo (TRUE) or return (FALSE) the tag.
        (Default: TRUE)


      Displaying the Comment Form: comment_form()

      This template tag displays the whole comment form.


      This template tag accepts two parameters:

      • $args (optional—array):
        An array of the following arguments:
        • 'fields' (array): An associative array of default comment fields' HTML codes ('author', 'email' and 'url').
          (Default: All three of them)
        • 'comment_field' (string): HTML code for the comment's TEXTAREA element.
        • 'must_log_in' (string): HTML code for the "must log in to comment" message.
        • 'logged_in_as' (string): HTML code for the "logged in as..." message. (Use %1$s for the profile URL, %2$s for the username and %3$s for the logout URL.)
        • 'comment_notes_before' (string): HTML code for the notes shown before the comment form.
        • 'comment_notes_after' (string): HTML code for the notes shown after the comment form.
        • 'id_form' (string): The ID of the comment form's FORM element.
        • 'id_submit' (string): The ID of the submit button.
        • 'name_submit' (string): The NAME parameter of the submit button.
        • 'title_reply' (string): Label for the "Leave a Reply" button.
        • 'title_reply_to' (string): Label for the "Leave a Reply to %s" button.
        • 'cancel_reply_link' (string): Text of the "Cancel Reply" link.
        • 'label_submit' (string): Label for the "Post Comment" button.
        • 'format' (string): The comment form format ('xhtml' or 'html5', default is 'xhtml').
      • $post_ID (optional—integer or object):
        The ID of the post.
        (Default: Current post)


      Displaying a Title for the Comment Form: comment_form_title()

      This template tag echoes a dynamic title for the comment form.


      This template tag accepts three parameters:

      • $noreplytext (optional—string):
        Text of the link if it's not a "reply to comment" link.
        (Default: 'Leave a Reply')
      • $replytext (optional—string):
        Text of the link if it's a "reply to comment" link.
        (Default: 'Leave a Reply to %s')
      • $linktoparent (optional—boolean):
        Whether to link the commenter's name to his/her comment or not.
        (Default: TRUE)


      Getting & Displaying the "Reply to Comment" Link: get_comment_reply_link() & comment_reply_link()

      These template tags let you return or display a reply link for the given comment.


      Both template tags accept three parameters:

      • $args (optional—array):
        An array of the following arguments:
        • 'add_below' (string): The first part of the selector used to identify the comment to respond below. The resulting value is passed as the first parameter to addComment.moveForm(), concatenated as $add_below-$comment->comment_ID.
          (Default: 'comment')
        • 'respond_id' (string): The selector identifying the responding comment. Passed as the third parameter to addComment.moveForm(), and appended to the link URL as a hash value.
          (Default: 'respond')
        • 'reply_text' (string): Text of the 'Reply' link.
          (Default: 'Reply')
        • 'login_text' (string): Text of the link to reply if logged out.
          (Default: 'Log in to Reply')
        • 'depth' (integer): Depth of the new comment—must be greater than 0 and less than the value of the 'thread_comments_depth' option set in Settings > Discussion.
          (Default: 0)
        • 'before' (string): HTML code to add before the output.
          (Default: Empty)
        • 'after' (string): HTML code to add after the output.
          (Default: Empty)
      • $comment_ID (optional—integer):
        The ID of the comment to work with.
        (Default: Current comment's ID)
      • $post_ID (optional—integer or object):
        The ID of the post.
        (Default: Current post)


      Getting & Displaying the Hidden Fields of the "Reply to Comment" Form: get_comment_id_fields() & comment_id_fields()

      These template tags echo or return the hidden and mandatory input fields of a "reply to comment" link.


      Both template tags accept only one parameter:

      • $post_ID (optional—integer):
        The ID of the post.
        (Default: Current post's ID)


      Getting & Displaying the "Cancel Reply" Link: get_cancel_comment_reply_link() & cancel_comment_reply_link()

      These template tags return or echo a "Cancel Reply" link for using with the comment reply form.


      Both template tags accept only one parameter:

      • $text (optional—string):
        Text to display as the "cancel reply" link.
        (Default: "Click here to cancel reply.")


      Getting & Displaying the Link for "Next Comments": get_next_comments_link() & next_comments_link()

      These template tags return or print the "next comments" link in your theme's Comments section.


      Both template tags accept two parameters:

      • $label (optional—string):
        Text to display for the link.
        (Default: 'Newer Comments »')
      • $max_page (optional—integer):
        Maximum page number.
        (Default: 0)


      Getting & Displaying the Link for "Previous Comments": get_previous_comments_link() & previous_comments_link()

      These template tags return or print the "previous comments" link in your theme's Comments section.


      Both template tags accept only one parameter:

      • $label (optional—string):
        Text to display for the link.
        (Default: '« Older Comments')


      Getting Pagination Links for the Comments: paginate_comments_links()

      This template tag returns the pagination links for your theme's Comments section.


      This template tag accepts only one parameter:

      • $args (optional—array):
        An array of the following arguments:
        • 'base' (string): Base URL to be used to create paginated links.
        • 'format' (string): The argument to use for replacing the page number.
        • 'total' (integer): Total number of pages.
        • 'current' (integer): Current page number.
        • 'echo' (boolean): Whether to echo the template tag or not.
          (Default: TRUE)
        • 'add_fragment' (string): Text to prepend the page URLs.
          (Default: '#comments')


      Getting & Displaying the "Edit Comment" Link: get_edit_comment_link() & edit_comment_link()

      These template tags return or echo a "edit this comment" link for you to use in your templates.


      get_edit_comment_link() accepts one parameter:

      • $comment_ID (optional—integer):
        The ID of the comment to work with.
        (Default: current comment's ID)

      And edit_comment_link() accepts three parameters:

      • $text (optional—string):
        Text to display the link.
        (Default: "Edit This")
      • $before (optional—string):
        The text or HTML code to display before the output.
        (Default: Empty)
      • $after (optional—string):
        The text or HTML code to display after the output.
        (Default: Empty)


      Getting & Displaying the "Comments Feed" Link: get_post_comments_feed_link() & post_comments_feed_link()

      These template tags return or display a link for the comments feed.


      get_post_comments_feed_link() accepts two parameters:

      • $post_ID (optional—integer):
        The ID of the post.
        (Default: Current post)
      • $feed (optional—string):
        Type of the feed.
        (Default: Default feed type)

      And post_comments_feed_link() accepts three parameters:

      • $link_text (optional—string):
        Text to display for the link.
        (Default: "Comments Feed")
      • $post_ID (optional—integer):
        The ID of the post.
        (Default: Current post)
      • $feed (optional—string):
        Type of the feed.
        (Default: Default feed type)


      Displaying a Link of the "Comments" Popup: comments_popup_link()

      This template tag displays a link of the "Comments" popup, in case you want to use popup links in post lists.


      This template tag accepts five parameters:

      • $zero (optional—string):
        Text to display if there are no comments.
        (Default: 'No Comments')
      • $one (optional—string):
        Text to display if there is only one comment.
        (Default: '1 Comment')
      • $more (optional—string):
        Text to display if there is more than one comment.
        (Default: '% Comments')
      • $css_class (optional—string):
        Extra CSS class names to add.
        (Default: Empty)
      • $none (optional—string):
        Text to display if comments are turned off.
        (Default: 'Comments Off')


      Displaying the "Comments" Popup Script: comments_popup_script()

      This template tag builds and prints the script of the "Comments" popup.


      This template tag accepts three parameters:

      • $width (optional—integer):
        Width of the popup window.
        (Default: 400)
      • $height (optional—integer):
        Height of the popup window.
        (Default: 400)
      • $file (optional—string):
        URL to display on the address bar of the popup.
        (Default: Home URL)



      Hope you liked this fourth batch of template tags. There are four more batches to go, so stay tuned for more template tags!

      If you have any questions, comments or corrections, you can share your thoughts with us in the Comments section. And if you liked the article, don't forget to share it with your friends!



      Leave a comment › Posted in: Daily

    1. Get Started With Monitoring Your Web Application Using New Relic Alerts


      Let's start with an extreme example. After three years on the market, according to analytics site Think Gaming's estimates, the tower defense hit game Clash of Clans is still the top grossing mobile game today, bringing in an astonishing $1.5 million a day—or a bit over $1,000 every minute. At the heart of the game is a cluster of web servers that take care of everything from user accounts to game events and processing payments.

      Imagine if one day the team pushed a new build that broke the payment processing.

      Every minute the bug went unnoticed would mean a loss of a thousand dollars! 

      Now, imagine this bug appeared during the night when there was no one at work...

      Your numbers are probably smaller, but the basic concept remains the same: If you make your living from running a web application, any issue with the service, be it a bug in the code or a problem with the server setup, means lost sales.

      Even worse: if the bug occurs in a piece of code that you don't test every day, such as the communication between your shopping cart and an external payment provider, it may be days before one of your customers emails you to let you know about the issue!

      This is where server monitoring comes to play. While running a good set of tests before every update certainly helps, you can never anticipate everything. You need eyes inside the server; monitoring tools that let you see the key metrics describing your server's health, from server bugs to slow loading times and calls to external services taking longer than they should. 

      But even monitoring isn't enough when you have a lot on your plate and forget to check your stats—or when problems arise during the night when you are sound asleep.

      That's what we'll talk about in this tutorial.

      In This Tutorial

      While there are various options for both software analytics and alerts tools, New Relic offers one of the most complete solutions for analyzing your servers. 

      New Relic recently started an open beta for a new product called New Relic Alerts—a layer on top of their set of monitoring tools that you can use to keep yourself and your team updated on any events in your application requiring your attention.

      In this tutorial, we'll use New Relic Alerts to create a set of alerts for monitoring a simple PHP application running on an Amazon EC2 instance. While doing this, we'll also talk about the general principles and best practices of defining software alerts to help you create the best possible alerting setup for your business needs.

      Set Up New Relic on Your Server

      Before you can start using New Relic Alerts, you'll need a New Relic account that has been set up to monitor a web service. 

      That's why, before we start configuring and testing alerts, I will quickly guide you through the steps of setting up monitoring on a newly created Amazon EC2 instance. For a more detailed look at using the monitoring tools in your own application, I suggest our free course, Monitoring Performance With New Relic

      Previous tutorials by Jeff Reifman and Alan Skorkin will also help you get up to speed. For more information about Amazon EC2, take a look at this tutorial about Installing WordPress in the Amazon Cloud.

      If you are already using New Relic on your server, you can skip past this section and continue from the next one, Get Started with New Relic Alerts.

      Step 1: Create a New Amazon EC2 Instance

      Choosing a server for your application is a question outside the scope of this tutorial. However, for experiments like this, I'm a big fan of AWS: using EC2, I can start and stop servers as I need them, only being charged for the time I use them.

      To create a test instance on Amazon EC2, first sign in to your Amazon Web Services admin Console (if you don't have an account yet, you will need to create one before continuing). Then, in the main menu, choose EC2 (Virtual Servers in the Cloud).

      On the EC2 Dashboard, click on the button labeled Launch Instance to start the process of creating a new server:

      Launch a new EC2 instance

      Next, you'll be asked to choose the Amazon Machine Image (AMI) for the virtual server you are about to start. For this tutorial, the default quick start option, Amazon Linux AMI 2015.03, is just what we need. 

      Click Select to pick that one.

      The default Amazon Linux AMI is good for what were doing

      After choosing the AMI, you'll be asked to Choose an Instance Type—basically the size of the machine. As we'll use the machine for experiments and learning, the smallest one, t2.micro, is a good one to go with:

      Pick the t2micro instance type

      Make sure you have checked the checkbox in front of the correct instance type. Then click Review and Launch to skip straight to the last step in the launch wizard.

      On that page, you'll see a notification about improving your security groups. 

      Review Instance Launch

      Click on Edit security groups to go back to the security group configuration step. There, make the following changes to your security groups:

      • Edit the existing SSH rule to limit SSH access to just your IP address (select My IP in the Source drop-down).
      • Add a new rule to open the HTTP port to everyone (select Anywhere in the Source drop-down).

      Here's how the security group settings should look with your changes in place:

      Example security group settings

      After making the changes, click on Review and Launch to get back to the Review Instance Launch page and launch the server.

      As the last step, Amazon will ask you to create a new key pair (or to pick an existing one) for connecting to the new server over SSH. Give the key pair a name, download it by clicking on Download Key Pair, and then click on Launch Instances

      Set up key pair

      On your computer, move the downloaded key pair file, e.g. test_keypair.pem, from the downloads directory to a better location, and change its access properties so that no one but you can open the file. 

      Here's an example of how to do this on Mac OS X:

      Now, to connect to the server, check the new instance's IP address from the Amazon EC2 dashboard and connect to it using the key pair file (replace the IP address with one matching your server):

      If your server is up and running, you should now be logged in. 

      Install PHP using the following command. Accept the suggested packages.

      Then start Apache:

      You have now created a simple Apache and PHP server setup on Amazon EC2. Next, let's start monitoring it using New Relic APM.

      Step 2: Enable New Relic APM on Your Server

      First, if you don't yet have a New Relic account, start by creating one. 

      On the signup page, fill in all of the fields, and then click on Sign Up for New Relic.

      SIgn up for New Relic

      Next, let's set up New Relic's web application monitoring tool, APM.

      On the welcome screen, click on the New Relic APM item:

      Welcome to New Relic

      After selecting APM, you'll see a page with instructions for enabling the monitoring in different environments. 

      If you are setting up New Relic on a server other than the Amazon EC2 based one we created in the previous step, this Get Started with New Relic page is where you're the most likely to find the instructions specific to your environment. 

      Also, while the installation commands used below are valid at the time of writing, it's a good idea to double-check this page for the most up-to-date instructions.

      Now, click on the PHP logo to reveal installation instructions for the PHP Agent.

      Get started with New Relic APM

      To install the PHP agent, first use SSH to connect to the EC2 instance we created above. 

      Then, in your SSH window, type the following command to add the New Relic repository (for the EC2 instance defined above, we use the 64-bit version):

      Then, to install the PHP agent:

      At the end of the installation, the script will ask you to enter your New Relic license key:

      Enter New Relic license key

      To get your license key, go back to the Get Started with New Relic page and click on Reveal license key.

      Get your license key

      Copy the key and paste it in the shell prompt to complete the installation.

      To apply the changes, restart the web server, and then wait for a few minutes so that New Relic will start receiving data from your server.

      Once New Relic APM is receiving data from your server, instead of the setup screen shown above, you'll see the APM Dashboard with your PHP Application listed on it:

      New Relic APM Dashboard

      Once this happens, you are ready to start using New Relic Alerts.

      Get Started With New Relic Alerts

      Now that you have set up your server and have New Relic APM keeping an eye on it, it's time to move to the actual topic of this tutorial: alerts.

      Step 1: Enable New Relic Alerts

      The first thing to do is to enable Alerts on your New Relic account. 

      Click on the AlertsBeta link on the top right corner of the New Relic window. Alerts is still a beta feature, so before getting started, you'll be presented with a screen describing its features as well as a list of things that are still being developed. 

      While most features are already in place, New Relic says Alerts will maintain its beta status until they have added "server not reporting" alerts, API support, and a method for migrating existing alerts to the new system.

      During the beta, it is still possible to use the new system side by side with legacy alerts, so even if you are an existing New Relic user, there is no harm in giving Alerts a try.

      Welcome to New Relic Alerts screen

      To start using New Relic Alerts, scroll down to the bottom of the page, tick the checkbox that says "I agree to accept the terms and conditions of the New Relic AlertsBeta" and click on the Try it out button.

      Enable New Relic Alerts beta

      Step 2: Create Your First Alert Policy

      After enabling Alerts, the first thing you'll see is a page for creating an alert policy.

      Create your first alert policy

      In New Relic Alerts, all alerts are grouped into alert policies that each have their own sets of notification channels. This means that when an alert condition is violated, an alert is sent to all users and communication channels specified in the policy.

      That's why the best way to think about alert policies is through the notifications. 

      Ask yourself two questions: 

      • Who needs to receive notifications from this set of alerts?
      • How should they receive the notifications?

      As an example, critical server issues that require immediate attention regardless of the time of day need to be sent to a different group of people and using a different notification channel (the phone buzzing to wake you up) than less severe performance issues that can be solved during the day (an email notification to tell you to start optimizing the code).

      But don't get stuck at this step for too long. If you can't think of a perfect way of organizing your alerts yet, that's OK: you can always come back to it and change your alert policies later as you get more familiar with the concept.

      In this tutorial, we'll start by creating a simple, all-encompassing alert policy that we'll just call "Application".

      Type the name in the text box that says Team name or service name and click on Create policy.

      Step 3: Get to Know the Alerts Dashboard

      You are now ready to start creating alerts for your application. But before we go there, let's take a quick look at the Alerts dashboard:

      Alerts dashboard showing alerts for the Application alert policy

      Starting from the left, the options are:

      • Incidents: A list of alert violations divided into two tabs. Open Incidents are alerts that have not yet been resolved and require your attention right now. All Incidents is a historical list you can use to look up past alert condition violations and to see what was done to fix them.
      • Events: A list of all events from the Alerts system, divided into two tabs. Violations shows all alert condition violations. Events also lists the notifications sent to different notification channels and changes in incident statuses.
      • Alert policies: This is the heart of the Alerts system, the set of rules that govern how and when alerts are sent.
      • Notification channels: This is where you configure the notification channels used in alert policies to notify you and your team about incidents in your application.

      The menu item that comes after these four, Switch to AlertsBeta, confused me at first. Because of its name, I got the impression that I hadn't yet enabled the new Alerts. That wasn't the case, however. Instead, this is an option you can use to go all-in and fully integrate the new Alerts system to your New Relic experience, leaving the legacy alerts behind.

      If you click on the menu item, you'll see the following page:

      Go all-in on New Relic Alerts

      This page gives you an overview of the changes that will take place if you switch completely to the new Alerts functionality. Most importantly, this means a deeper integration to Alerts in the other New Relic products. 

      If you are already a New Relic user and your current application relies on the legacy alerts system, you might want to think twice before moving on. Also, to follow through the rest of this tutorial, you don't need to go this far—as I mentioned earlier, it's perfectly OK to use the two systems side by side.

      But if you're adventurous and like to use the bleeding edge versions of your software, you can very well accept the fact that there is no going back and switch your account to use only the new Alerts functionality by clicking on the Become an early adopter button at the bottom of this screen.

      Become an early adopter

      The choice is yours. And whichever way you decide to go, you are now ready to create your first alert.

      Create Your First Alert

      Now that you have enabled New Relic Alerts and have an overall understanding about the tool, it's time to get to work and create your first alert: an alert that sends a notification using email and Slack if the error rate in your PHP application exceeds 5% at least once in 5 minutes. 

      I chose this alert because it is an important one, but also because it is easy to test: once the alert condition has been defined, we can break the server and cause the alert to fire without much extra work.

      But first, let's talk a little about what makes a good software alert.

      Step 1. Decide the Issues You Want to Receive Alerts About

      In Aesop's classic fable, The Boy Who Cried Wolf, a bored shepherd boy again and again cries out false alarms about a wolf attacking his flock. In the end, when a wolf finally does appear, the villagers think it's just another false alarm and no one come to his rescue.

      Likewise, if you have a software alert that notifies you every day—or even worse, many times a day—about something that you don't need to act on right at that moment, you get used to ignoring the error. Then, when important errors finally arise, they are lost in the noise and you miss them.

      This is why you should always start planning your alerts by asking yourself: "How important is this alert?" and "How will I (or my team) react to this alert?"

      Your answer, then, will guide what you do next:

      • If the alert is something that needs to be addressed immediately, add it to an alert policy that wakes you (or your team) up at any time of the day.
      • If the alert is something urgent that can be solved in one day or less, include it in an alert policy that notifies you through a less intrusive notification channel such as email.
      • If the alert doesn't require attention in a day or two, it's probably best not to create an alert at all. The issue will be noticed during a casual look at the monitoring tools and can then be marked as a task in your project management tool for later consideration.

      Also, make sure that you send the alerts to people who have the means to do something about them. A manager's inbox filling with alerts about bugs in the code is nothing but a distraction.

      Another thing to consider is the alert threshold, or questions like:

      • How soon should an alert be sent? 
      • What's an acceptable error percentage?
      • How low can a server's disk space go before we need to do something about it?

      This is not an easy task, and it will probably take some tinkering before you get your set of alerts defined just right. You want to send the error message early enough that you don't miss important errors, but not so soon that you get too many false alerts. 

      The best way to go about this is through experimentation: changing alert conditions is quick, as it doesn't involve changing configuration files and server restarts, so keep trying out different values until you are happy with the results. Also, as your application evolves, you'll probably want to change your alerts as well, for example loosening alert thresholds when you know a new update will negatively affect your loading times for a while.

      Step 2: Select the Product and Target to Monitor

      As I explained earlier, every alert condition in New Relic Alerts belongs to an alert policy. So, to add a new alert condition, first navigate to the Alert policies tab and select the policy you just created, "Application"

      As you haven't yet created any alert conditions, you'll see the following placeholder in the middle of the page:

      No conditions yet

      Click on Create a condition to start defining your first alert condition. After you have created this first condition, you'll see a list of alert conditions instead of the big button—at that point, adding a new condition is initiated using a smaller New alert policy button on the top right corner of the list.

      Clicking on the button initiates a three-step New condition wizard: 

      Select a product for the alert

      In the wizard, you'll be first asked to select a New Relic product. This is the product that you'll use as the source of metrics for the alert condition you are creating, and that therefore will also define the options available for you in the next two steps in the wizard. 

      PHP errors are monitored using APM, so let's pick that one.

      On the same wizard step, you still have a second choice: selecting the type of condition you want to create. The options in this selection change as you switch between products. For APM you have the following three options:

      • Application metric: This option gives you access to the default application metrics measured by APM (Apdex, Error percentage, Response time, and Throughput) as well as any custom metrics you have defined in the monitoring tool.
      • Key transaction metric: As a paid feature in APM, you can mark some of the transactions in your application as "key transactions"—transactions that have special importance for your business or your product. If you select this option, you will create the alert condition in the same way as you would using the Application metric option, except that instead of monitoring the entire application (or multiple applications), the alert will only fire if the condition is met within a key transaction you select.
      • External service: This option lets you create alert conditions based on API or other calls made to external services. 

      As error percentage is an application metric and we haven't specified any key transactions, select Application metric and click on Next, select targets to move to the second step in the wizard.

      Select application to monitor

      On this second screen, you will select the APM monitored applications that the alert condition should notify you about.

      First, click on All Applications to reveal the list of applications. 

      Then, tick the check box in front of our application (in our example, we only have one application, PHP Application) and move to the final step in the wizard by clicking on the Next, define thresholds button. 

      Step 3: Define the Alert Condition

      The third and final step in the New condition wizard is where you define the actual alert condition. 

      Define the alert condition

      The options you'll see in this step depend on the choices you made in the first two steps. However, in each case, the basic idea is the same: this is the screen on which you'll select a metric and an error (and an optional warning) threshold for it.

      To create the high error percentage alert condition I described above:

      1. Select Error percentage as the application metric to monitor.
      2. Then, pick a suitable comparison operator. In this case, above makes the most sense (the other options are below and equal to).
      3. Define the threshold: what's an error percentage that makes sense for an error report? Make this number too high and you'll miss important errors. Make it too low and you'll drown in alerts. 5% is a good starting point, but in real life you may end up tweaking the threshold up or down depending on your application and your preferences.
      4. Define the time frame: To catch the most errors, choose "at least once in" "5 mins". This will alert you immediately if the error threshold is exceeded even once during the selected time frame. On the other hand, if you want to give your application a bit more slack, you can choose "for at least" and only receive the notification if the error percentage stays high for the entire duration of the selected time frame.
      5. If you like, you can also define a warning threshold using a lower error percentage. Warnings will not trigger email alerts but you'll see them in the list of events as well as in the APM view (if you have gone all-in and become an early adopter—see discussion earlier in this tutorial).
      6. Give the condition a descriptive name or—if you are satisfied with it—use the default name suggested by the tool.
      7. If you want to provide your team with information about the incident and how to fix it, you can add a "runbook URL": a link to an outside web page, for example a documentation page that explains what this alert means and describes the steps to solve it. To do this, click on Add runbook URL and enter the URL in the text field.

      When you're happy with the alert condition, click Create condition to save it. Remember that you can always come back to tweak it later.

      Now, the Alert conditions page will look like this, with your new alert added to it:

      Alert condition added

      If at any time, you want to modify the alert condition, just click on its rules. Notice also the Copy and Delete buttons on the top right corner of your new alert condition: these come in handy if at some point you want to move the alert to a different alert policy.

      Step 4: Set Up Email Notifications for the Alert Policy

      You have now created the first alert. But an alert without a notification channel isn't very useful: the violations will be added to the incidents tab, but no one gets notified. To make the alert policy notify you about an incident, we'll need to define a notification channel and link it to this alert policy. 

      Let's start with the most common one, email.

      To start creating your first notification channel, click on the Notification channels menu item. Then, click on the big button that says Create a notification channel.

      No notification channels configured yet

      On the next screen, you'll first see a text box that says "Select a channel type". Click on it to reveal a drop-down list with the available notification options:

      Select the type of notification channel to create

      The options available at the moment (according to the documentation, more channels will be added in the future) are:

      • E-mail: Sends an email message to the email address specified in the configuration. 
      • HipChat: Sends a message to the HipChat room specified in the configuration.
      • PagerDuty: Sends a notification through the NetOps administration tool PagerDuty. This is an advanced option for the more critical notifications that need to addressed immediately—the alerts can even be configured to call you on the phone!
      • VictorOps: Similar to PagerDuty, this option sends a notification through the NetOps tool VictorOps. The functionality in the two tools is quite similar, so the choice depends mostly on what you're already using.
      • Webhook: Sends a notification to a URL you define. Use this option if you want to send notifications to a channel that isn't currently supported directly by New Relic Alerts—or if you want to create your own custom solution...
      • Campfire: Sends a notification to the Campfire chat room specified in the configuration.
      • Slack: Sends a notification to the Slack channel specified in the configuration. 
      • OpsGenie: Sends a notification using the OpsGenie NetOps alert system. OpsGenie is another tool similar to PagerDuty and VictorOps that can be used to make sure your team notices the alerts as they arise.

      In addition to these, New Relic Alerts automatically creates a Users notification channel for every user in your account. This channel can be used to send email and to push notifications to New Relic's iPhone and Android application.

      In a real-world situation, you should pick tools that are the best fit with your Alert policy and your team's communication culture: for example, using OpsGenie for the urgent alerts and email for the not so urgent ones. In this tutorial, we'll just add two as an example, starting with email.

      When you click on the E-mail option, the rest of the form is automatically updated to show the email notification configuration:

      Create an e-mail notification channel

      Enter your email address in the Email field and click on Create channel. If you want to send some more data about the incident along with the email message (for example if the email is read programmatically), check the Include JSON attachment check box.

      And that's it, an email notification channel has now been created:

      The e-mail notification channel was created successfully

      To attach this notification channel to the alert policy you created earlier, return to the Alert policies page and select the "Application" alert policy.

      Then, click to view the Notification channels tab. As there are no notification channels defined for this alert policy yet, the tab will look like this:

      The policy doesnt have any notification channels yet

      Click on Add notification channels to open a pop-up window for selecting the notification channels to be used in this alert policy.

      Select the e-mail notification channel

      Use the notification channel browser to locate the E-mail channels and check the checkbox in front of your email address. 

      Then click Update policy to save the changes.

      Step 5: Set Up Slack Notifications for the Alert Policy

      Next, let's make the notifications appear on a Slack channel. If you don't use Slack, you can skip this step and move on to the next step, in which we'll start testing the alert.

      Creating a Slack notification channel is a little more complicated than the email setup we did above, but not difficult at all. Notice, however, that while you'll find a New Relic integration option on your Slack integrations tab, that one is for legacy alerts and won't work with the new Alerts yet.

      For now, to post notifications to a Slack channel, we'll need to use a WebHook defined in the Slack settings. Here's how you do it.

      First, in your Slack chat window, click on the down arrow next to your user name to open the menu. Then, select the option Configure Integrations:

      In Slack click on Configure Integrations

      This will open a new browser tab showing Slack's Integrations page.

      Scroll down to the Incoming WebHooks option and click Add.

      Select the Incoming WebHooks option

      You'll be directed to a new page with information about the integration. 

      Slack Webhook setup instructions

      Scroll down to Setup Instructions and copy the URL next to the label Webhook URL. This is a unique, generated URL and should only be used for this one integration. If you have any reason to suspect that the URL has leaked to someone who shouldn't have it, you can (and should) generate a new one.

      Return to the New Relic Alerts Notification channels page and create a new notification channel selecting Slack as the Channel type. In this new channel's options, insert the URL you just copied into the text field labeled URL:

      Configure the Slack notification channel

      If you like, you can use the Team channel field to define the name of the Slack channel you want the notifications to be posted to. If you do this, make sure you remember to include the hash sign in front of the name—otherwise, instead of receiving an alert on your Slack channel, you'll just see an error in the Events log.

      Click on Update channel to save the definition. Then, follow the steps of linking the new notification channel to your alert policy that we used when linking the email.

      Step 6: Test the Alert by Making Your Code Fail

      Before I leave you to work on your real-world alerts and setting up your production server, let's put our new alert to the test and see what happens when an alert condition is violated. 

      As we created a test server specifically for this tutorial's needs, we can safely break the code. If you are testing the alerts on an existing server of yours, you probably only want to do this in a testing or staging environment.

      To create a PHP error in the server setup we created earlier, first use SSH to connect to your server. Then, jump to your web server's root directory:

      In this directory, create a PHP file, for example error.php, and write some faulty code to make the script break when you try to load it in your browser:

      Now, open the URL in your web browser, and refresh it a few times during the five minute time frame we defined for the alert condition. (You'll find your server's URL in the Amazon EC2 dashboard.)

      After about five minutes, you should receive a notification both in your email inbox and the Slack channel you defined above.

      Here's how the error will look in your email:

      The alert notification email message

      And the same notification in Slack:

      Alert notification in Slack

      When you click on the View incident details link in the email or the incident number in Slack, you will be redirected to the corresponding New Relic Alerts page with a lot more information about the issue that caused the notification:

      View incident details

      If you are ready to start working on the alert, click on the Acknowledge button on the right. After you have clicked on the button, it is replaced by the following piece of state information:

      Incident acknowledged

      You (and your team, as configured in the notification channels) will also receive a notification about the acknowledgement via email and Slack. This acknowledgement means that you take ownership in fixing the issue, and the status cannot be changed: once you have acknowledged an alert, no one else can acknowledge it again.

      When you scroll down to the bottom of the alert page, you'll see the following buttons that you can use to get more information about solving the issue (Open runbook), Edit alert condition (if you believe this is a false alert) or Manually close violation (once you have fixed the issue).

      Incident actions

      For a lot more information about the issue, you can also visit APM's Errors page:

      More information about the error

      Use the information from APM to fix the problem (this time, it's easy). 

      Then load the page a few times again and wait for another notification telling you that the issue is no longer active, or go back to the Incidents page and click on Manually close violation to close the alert immediately. 

      As New Relic Alerts is driven by data, if no more data comes from your server after the alert was sent, the incident stays open forever. So, if you are wondering about why your alert is not getting closed automatically even after you fixed the bug on this test server, it's because no one is using the site—and therefore there's nothing to be worried about.

      You have now successfully created your first alert condition and used it to fix a bug in your server, and you are ready to start creating your real-world alert policies to keep your web application safe. 

      Other Metrics for Your Alerts

      While the error notification we just created is a highly useful one, it's still only one of many alerts you can create using New Relic Alerts. 

      To help you as you proceed with developing your own set alerts for a real web application, here are the rest of the options applicable to web applications, along with some ideas for issues in your application you might want to monitor using them.

      1. Alert Conditions Based on APM Metrics

      APM (short for Application Performance Monitoring) is New Relic's flagship product: an application monitoring tool that goes down to the code level, measuring things like errors and how long your application takes at various points in execution.

      In addition to the high error percentage alert condition we created above, the following APM metrics can be used for creating alerts.

      • Apdex: Apdex (Application Performance Index) is a standard method defined for measuring and comparing the performance of software applications. The metric measures end user satisfaction and goes from 0 to 1, where 1 means that every user is satisfied and 0 means that no one is. A good number to start from is 0.7, which is the default alert threshold in the legacy New Relic alerts.
      • Response Time and Throughput: Response time tells you how long requests made to your application take on average. Throughput is a related metric that describes how many requests were successfully processed by your service during a given time frame. While both metrics are incorporated in the Apdex calculation, adding alerts for them will make your alerts more specific and thus easier to analyze and direct to the right people.
      • Custom Metric: If you are recording your own custom metrics in APM, you can use them to create your own application-specific alert conditions.
      • External Service: Using the external service condition type, you can create alerts based on the response time and throughput from an HTTP call to an external service. For example, on my own site, monitoring the external service requests helped me identify an API call to Tumblr as a major reason for slow loading times.

      If you select Key transaction metrics (paid feature in APM) as your Type of condition, you'll have access to all the same metrics described in the list above, but they'll be used for tracking just the selected transactions and not the entire application. 

      This way, you can have alerts about errors in important transactions (such as payment processing) sent with higher priority (SMS instead of email, for example) than errors in less critical transactions.

      2. Alerts Based on Browser Metrics

      Browser is a New Relic monitoring product designed to give you a view of how real users experience your web application: monitoring for the things that happen inside the browser. For a more detailed explanation of the tool and instructions on enabling it on your New Relic account, check out this tutorial.

      Whereas APM-based alerts notify you about things that go wrong inside the application server, Browser alerts can be important in pinpointing errors that cause the user experience to break.

      • End User Apdex: The key metric in Browser based alerts, End User Apdex measures the percentage of users who are satisfied by the application's performance, taking into account also the performance of the application as it runs in the browser.
      • Page Load Time: A group of metrics for measuring the time spent at different parts of page loading: total page load time, page rendering, web application, network, DOM processing, and request queueing can all be used to get more detailed alerts about specific bottlenecks in the end user experience.
      • Page Views with JavaScript Errors: The number of JavaScript errors in your application can be a sign of bad programming that should be addressed quickly. Using this metric, you can create an alert similar to the error percentage alert we created in this tutorial—only this time, measuring JavaScript errors instead of errors in the application PHP code.
      • AJAX Response Time and Throughput: If your application uses AJAX calls for important end-user-facing actions, it's important to find problems in them early on. For this, you can use the metrics measuring how long AJAX requests take to process and how many AJAX requests are successfully served in a given time frame. 
      • Custom Metric: Just like in APM alerts, you can also use custom metrics in your Browser alerts.

      3. Alerts Based on the Servers Metrics

      Servers is New Relic's product for measuring what happens physically on your server. Instead of looking at the application metrics as we did with APM and Browser, now we're talking about things like disk space usage and CPU load—the kinds of metrics you want your NetOps team (or just you, if you're a small operation) to always stay on top of. See this tutorial for more information about New Relic Servers.

      These metrics are all important sources for—usually urgent—alerts:

      • CPU %: If your application uses a lot of the CPU resources, it could be a sign that you need to either optimize the application or move it to a more powerful server. In both cases, it's good to know when you reach the limits of what the machine can handle.
      • Disk IO%: In New Relic Servers, the disk IO% metric tells you how much of the time your disks are in use, 0% meaning no disk operations at all and 100% that the disk is in use all the time. 
      • Memory %: Especially when working on a data-heavy application, memory is one of the first resources you'll need to worry about. Make sure you get a notification early enough, before the machine runs out of free memory.
      • Fullest Disk %: When your server runs out of hard drive space, you can be sure your application will not perform as it should. Again, it's better to handle a disk space issue before it affects your users: around 90% full or so. 
      • Load Average: Load average tells you how well the server's CPU is coping with the work it is charged with. A value of 0 means a totally idle computer, and every running or waiting process adds to the number. The alert threshold depends on how many cores your server has: on a single-core system, a load average of 1 means that the CPU is used at full capacity (with two cores, the number is 2, and so on). Higher values mean that there are some processes waiting in line.

      What's Next?

      We have now looked at how alerts can help you monitor your web application and give you peace of mind, discussed the basics of designing good alerts, and gone through the steps of using New Relic Alerts to set up alerts for your web application.

      If you like to tinker, Alerts gives you a wide range possibilities to tweak and fine tune your alerts until they are just right: add some custom metrics to your code, use data from New Relic plugins, and send alerts to all kinds of different notification channels—or if you are a mobile developer, take a look at mobile alerts. We have only scratched the surface.

      Alerts is currently in beta, which means that new features are still being implemented as we speak. So, to stay updated on the new developments, keep an eye on the New Relic Alerts documentation and join the discussion on the tool's discussion forums.

      But first, go ahead and create some alerts!



      Leave a comment › Posted in: Daily

  • Page 1 of 75 pages  1 2 3 >  Last ›
  • Browse the Blog


    Most recent entries