How to print a debug log?

  • error_log(print_r($variable, TRUE)); 

    might be useful

  • You can use error_log to send to your servers error log file (or an optional other file if you'd like)

  • If you are on Linux:

    file_put_contents('your_log_file', 'your_content');


    error_log ('your_content', 3, 'your_log_file');

    and then in console

    tail -f your_log_file

    This will show continuously the last line put in the file.

  • You need to change your frame of mind. You are writing PHP, not whatever else it is that you are used to write. Debugging in PHP is not done in a console environment.

    In PHP, you have 3 categories of debugging solutions:

    1. Output to a webpage (see dBug library for a nicer view of things).
    2. Write to a log file
    3. In session debugging with xDebug

    Learn to use those instead of trying to make PHP behave like whatever other language you are used to.

  • Are you debugging on console? There are various options for debugging PHP. The most common function used for quick & dirty debugging is var_dump.

    That being said and out of the way, although var_dump is awesome and a lot of people do everything with just that, there are other tools and techniques that can spice it up a bit.

    Things to help out if debugging in a webpage, wrap <pre> </pre> tags around your dump statement to give you proper formatting on arrays and objects.


    <div> some html code ....
          <a href="<?php $tpl->link;?>">some link to test</a>
          dump $tpl like this:
        <?php var_dump($tpl); ?>

    And, last but not least make sure if debugging your error handling is set to display errors. Adding this at the top of your script may be needed if you cannot access server configuration to do so.

    ini_set('display_errors', '1');

    Good luck!

  • If you don't want to integrate a framework like Zend, then you can use the trigger_error method to log to the php error log.

  • Simply way is trigger_error:

     trigger_error("My error");

    but you can't put arrays or Objects therefore use


  • You can also write to a file like this:

    $logFilePath = '../logs/debug.text';
    // if you want to concatenate:
    if (file_exists($logFilePath)) {
    // for timestamp
    $currentTime = date(DATE_RSS);
    // echo log statement(s) here
    echo "\n\n$currentTime - [log statement here]";
    $logFile = fopen($logFilePath, 'w');
    fwrite($logFile, ob_get_contents());

    Make sure the proper permissions are set so php can access and write to the file (775).

  • You can use the php curl module to make calls to This works great in an secure, corporate environment where certain restrictions in the php.ini exists that restrict usage of file_put_contents.

  • This a great tool for debugging & logging php: PHp Debugger & Logger

    It works right out of the box with just 3 lines of code. It can send messages to the js console for ajax debugging and can replace the error handler. It also dumps information about variables like var_dump() and print_r(), but in a more readable format. Very nice tool!

  • I have used many of these, but since I usually need to debug when developing, and since I develop on localhost, I have followed the advice of others and now write to the browser's JavaScript debug console (see

    That means that I can look at the web page which my PHP is generating in my browser & press F12 to quickly show/hide any debug trace.

    Since I am constantly looking at the developer tools for debugger, CSS layout, etc, it makes sense to look at my PHP loggon there.

    If anyone does decide to us that code, I made one minor change. After

    function debug($name, $var = null, $type = LOG) {

    I added

    $name = 'PHP: ' . $name;

    This is because my server side PHP generates HTML conatining JavaScript & I find it useful to distinguish between output from PHP & JS.

    (Note: I am currently updating this to allow me to switch on & off different output types: from PHP, from JS, and database access)

  • I use cakephp so I use:

    $this->log(YOUR_STRING_GOES_HERE, 'debug');

  • You can use:

    echo '<script>console.log("debug log")</script>';

  • You can use


    or if you want to print that statement in an log you can use

    AddLog("anypage.php","string: ".$string,ERR_DEBUG_LOW);



  • S

    I'm working on A star algorithm and I'm trying to understand this code below. Here in this section of defining the map of obstacles to the PC, I didn't understand what does exactly here?.

    obmap = [[False for i in range(xwidth)] for i in range(ywidth)] for ix in range(xwidth): x = ix + minx for iy in range(ywidth): y = iy + miny # print(x, y) for iox, ioy in zip(ox, oy): d = math.sqrt((iox - x)**2 + (ioy - y)**2) if d <= vr / reso: obmap[ix][iy] = True break

    Here is an A star algorithm python code. In the part of defining the map of obstacles, I couldn't understand what are these lines will do exactly.

    Here is the python code of the A-star algorithm

    import matplotlib.pyplot as plt import math show_animation = True class Node: def __init__(self, x, y, cost, pind): self.x = x self.y = y self.cost = cost self.pind = pind def __str__(self): return str(self.x) + "," + str(self.y) + "," + str(self.cost) + "," + str(self.pind) def calc_final_path(ngoal, closedset, reso): # generate final course rx, ry = [ngoal.x * reso], [ngoal.y * reso] pind = ngoal.pind while pind != -1: n = closedset[pind] rx.append(n.x * reso) ry.append(n.y * reso) pind = n.pind return rx, ry def a_star_planning(sx, sy, gx, gy, ox, oy, reso, rr): """ gx: goal x position [m] gx: goal x position [m] ox: x position list of Obstacles [m] oy: y position list of Obstacles [m] reso: grid resolution [m] rr: robot radius[m] """ nstart = Node(round(sx / reso), round(sy / reso), 0.0, -1) ngoal = Node(round(gx / reso), round(gy / reso), 0.0, -1) ox = [iox / reso for iox in ox] oy = [ioy / reso for ioy in oy] obmap, minx, miny, maxx, maxy, xw, yw = calc_obstacle_map(ox, oy, reso, rr) motion = get_motion_model() openset, closedset = dict(), dict() openset[calc_index(nstart, xw, minx, miny)] = nstart while 1: c_id = min( openset, key=lambda o: openset[o].cost + calc_heuristic(ngoal, openset[o])) current = openset[c_id] # show graph if show_animation: # pragma: no cover plt.plot(current.x * reso, current.y * reso, "xc") if len(closedset.keys()) % 10 == 0: plt.pause(0.001) if current.x == ngoal.x and current.y == ngoal.y: print("Find goal") ngoal.pind = current.pind ngoal.cost = current.cost break # Remove the item from the open set del openset[c_id] # Add it to the closed set closedset[c_id] = current # expand search grid based on motion model for i, _ in enumerate(motion): node = Node(current.x + motion[i][0], current.y + motion[i][1], current.cost + motion[i][2], c_id) n_id = calc_index(node, xw, minx, miny) if n_id in closedset: continue if not verify_node(node, obmap, minx, miny, maxx, maxy): continue if n_id not in openset: openset[n_id] = node # Discover a new node else: if openset[n_id].cost >= node.cost: # This path is the best until now. record it! openset[n_id] = node rx, ry = calc_final_path(ngoal, closedset, reso) return rx, ry def calc_heuristic(n1, n2): w = 1.0 # weight of heuristic d = w * math.sqrt((n1.x - n2.x)**2 + (n1.y - n2.y)**2) return d def verify_node(node, obmap, minx, miny, maxx, maxy): if node.x < minx: return False elif node.y < miny: return False elif node.x >= maxx: return False elif node.y >= maxy: return False if obmap[node.x][node.y]: return False return True def calc_obstacle_map(ox, oy, reso, vr): minx = round(min(ox)) miny = round(min(oy)) maxx = round(max(ox)) maxy = round(max(oy)) # print("minx:", minx) # print("miny:", miny) # print("maxx:", maxx) # print("maxy:", maxy) xwidth = round(maxx - minx) ywidth = round(maxy - miny) # print("xwidth:", xwidth) # print("ywidth:", ywidth) # obstacle map generation obmap = [[False for i in range(ywidth)] for i in range(xwidth)] for ix in range(xwidth): x = ix + minx for iy in range(ywidth): y = iy + miny # print(x, y) for iox, ioy in zip(ox, oy): d = math.sqrt((iox - x)**2 + (ioy - y)**2) if d <= vr / reso: obmap[ix][iy] = True break return obmap, minx, miny, maxx, maxy, xwidth, ywidth def calc_index(node, xwidth, xmin, ymin): return (node.y - ymin) * xwidth + (node.x - xmin) def get_motion_model(): # dx, dy, cost motion = [[1, 0, 1], [0, 1, 1], [-1, 0, 1], [0, -1, 1], [-1, -1, math.sqrt(2)], [-1, 1, math.sqrt(2)], [1, -1, math.sqrt(2)], [1, 1, math.sqrt(2)]] return motion def main(): print(__file__ + " start!!") # start and goal position sx = 10.0 # [m] sy = 10.0 # [m] gx = 50.0 # [m] gy = 50.0 # [m] grid_size = 1.0 # [m] robot_size = 1.0 # [m] ox, oy = [], [] for i in range(60): ox.append(i) oy.append(0.0) for i in range(60): ox.append(60.0) oy.append(i) for i in range(61): ox.append(i) oy.append(60.0) for i in range(61): ox.append(0.0) oy.append(i) for i in range(40): ox.append(20.0) oy.append(i) for i in range(40): ox.append(40.0) oy.append(60.0 - i) if show_animation: # pragma: no cover plt.plot(ox, oy, ".k") plt.plot(sx, sy, "xr") plt.plot(gx, gy, "xb") plt.grid(True) plt.axis("equal") rx, ry = a_star_planning(sx, sy, gx, gy, ox, oy, grid_size, robot_size) if show_animation: # pragma: no cover plt.plot(rx, ry, "-r") if __name__ == '__main__': main()

    read more
  • S

    Already its been answered, but just adding another way of doing it.

    import pandas as pd import numpy as np c = ['Val1','Val2'] v = [ ['b',1.0], ['a',1.0], ['a',1.0], ['a',0.98], ['a',0.78], ['a',0.70], ['b',0.97], ['b',0.67], ['b',0.75], ] df = pd.DataFrame(v,columns=c) ##### Output #### Val1 Val2 0 b 1.00 1 a 1.00 2 a 1.00 3 a 0.98 4 a 0.78 5 a 0.70 6 b 0.97 7 b 0.67 8 b 0.75 k = df.groupby(['Val1']).apply(pd.DataFrame.sort_values, 'Val2',ascending=False) print(k) ##### Output #### Val1 Val2 Val1 a 1 a 1.00 2 a 1.00 3 a 0.98 4 a 0.78 5 a 0.70 b 0 b 1.00 6 b 0.97 8 b 0.75 7 b 0.67

    read more
  • S

    You can do:

    df[df.groupby('Val1')['Val2'].rank(method='dense',ascending=False)<=3] #or df[df.groupby('Val1')['Val2'].apply(lambda x: x.rank(method='dense',ascending=False)<=3)] Val1 Val2 0 a 1.00 1 a 1.00 2 a 0.98 3 a 0.78 5 b 0.97 7 b 0.75 8 b 1.00

    read more
  • S

    I have Data Frame Like this

    Val1 Val2 0 a 1.0 1 a 1.0 2 a 0.98 3 a 0.78 4 a 0.70 5 b 0.97 6 b 0.67 7 b 0.75 8 b 1.0

    I want to do groupby on Val1 and arrange val2 in decending order and take top unique value of every group.

    like this

    Val1 Val2 0 a 1.0 ----------- top1 of a 1 a 1.0 ----------- top1 of a 2 a 0.98 ----------- top2 of a 3 a 0.78 ------------ top3 of a 5 b 0.97 7 b 0.75 6 b 0.67

    So as you can see if the value is the same in field , it should consider it top 1st only.

    I tried this,


    But it is not giving expected as i understand that head is just taking 3 value from top. and i also tried nlargest is also not giving me expected result.

    read more
  • S

    I have a model that includes a ImageField along with other data (int, text, etc). And I have an API with method POST to create data with image file.

    Problem is, how to test this POST API that includes imagefield. Want to create fake image in test file instead of real file and how to test this along with other data.

    class CategorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Category fields = ( 'id','name','description','parent_id','start','end') read_only_fields = ('id','name','description','parent_id','start','end',) class ServiceProviderSerializer(serializers. HyperlinkedModelSerializer): category = CategorySerializer(many=True, read_only=True) class Meta: model = ServiceProvider fields = ( 'id', 'country_code', 'city', 'zip_code', 'service_type', 'preferred', 'display_bann', 'detail_name', 'detail_address', 'detail_description1', 'detail_description2', 'photo', 'category', ) read_only_fields = ('id',) def create(self, validated_data): """ Overriding the default create method of the Model serializer. """ # category_data = validated_data.pop('category') category_data = self.context['request'].data.get('category') service_provider = ServiceProvider.objects.create(**validated_data) category_data = json.loads(category_data) for category in category_data: categoryObj = Category.objects.get(pk=category['id']) service_provider.category.add(categoryObj) return service_provider

    def setUp(self): self.new_service_provider = { 'country_code': "DE", 'city': "FRANKFURT AM MAIN", 'zip_code': 60435, 'service_type': "Fitness Studio", 'preferred': True, 'display_bann': "?", 'detail_name': "City Fitness Frankfurt", 'detail_address': "Trakehner Str. 5, 60487 Frankfurt am Main", 'detail_description1': "Based on review, we suggest you to go to this studio", 'detail_description2': "", 'category':[{'id'}] } def test_post_service_provider(self): self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.adminUser.auth_token.key) # get API response response = reverse('service_provider-create'), data=self.new_service_provider, content_type='multipart/form-data' ) print( self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    Currently, I have not included field name photo, since I don't know how to mock it.

    read more